New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

Templ8

Package Overview
Dependencies
Maintainers
0
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

Templ8

JavaScript Client/ Server Template Engine

  • 0.1.7
  • npm
  • Socket score

Version published
Weekly downloads
21
decreased by-75.86%
Maintainers
0
Weekly downloads
 
Created
Source

#TODO:

  • documentation is not yet complete
  • add unit tests (already have tests: just wanting to port them from my own framework to an existing one like JSTestDriver or something).

Templ8

Templ8 as you can probably guess is a JavaScript template engine, with a Django'ish style of syntax.

It's fast, light weight (5kb gzipped & minified) and unlike most other JavaScript template engines: Templ8 does not use the JavaScript with statement . This actually makes Templ8 parse faster than it would if it did use the with statement!

Templ8 does not restrict you to generating HTML. All outputs are strings so if you want to generate HTML, CSS, JavaScript or whatever, the choice is yours...

Usage

Templ8 is avaiable as a Node JS module as well as a browser micro-framework.

Node

Installation
   npm install Templ8
Requiring
   var Templ8 = require( 'Templ8' );

Browser

You have 2 options.

  1. Templ8.client.js is the version optimised for modern browsers (i.e. browsers that implement JavaScript version 1.6).
  2. Templ8.shimmed.js contains shims to enable backwards compatibility with older browsers -- only an extra 0.5kb (min + gzip).

NOTE: The shimmed version will still use JavaScript 1.6 features where available.

API

If all you want to do is swap out values you can use one of the following two smaller template functions.

<static> Templ8.format( template:String, param1:String[, param2:String, ..., paramN:String] ):String

This function takes a minimum of two parameters. The first is the template you want perform substitutions over.

The template should use zero based tokens, e.g. {0}, {1} ... {N} that increment for each argument passed to the function.

e.g.

    Templ8.format( 'Hello {0}! Nice {1} we\'re having.', 'world', 'day' );

returns: Hello world! Nice day we're having.


 

<static> Templ8.gsub( template:String, dict:Object[, pattern:RegExp] ):String

gsub works similarly to format only it takes an Object with the values you want to substitute, instead of a sequence of parameters. Actually format calls gsub internally.

e.g.

    Templ8.gsub( 'Hello {name}! Nice {time} we\'re having.', { name : 'world', time : 'day' } );

returns: Hello world! Nice day we're having.

The default pattern for substitutions is /\{([^\}]+)\}/g. However, you can supply a third argument to gsub which is your own custom pattern to use instead of the default.

If you want to do fancy stuff, you'll want to use the Templ8 constructor.


 

new Templ8( template:String, options:Object )

The Templ8 constructor actually takes an arbitrary number of String arguments which form the template body.

The last argument to the Templ8 can -- optionally -- be a configuration Object which defines any custom Filters you want to use for this Templ8 and any sub Templates it contains.

It also accepts the following four parameters (needless to say that these cannot be used as Filter names):

compiledIf this is set to true then the Templ8 will be compiled straight away, otherwise it will wait until the first time you call it's parse() method to compile. Default is false.
fallbackThis is the String to use as a fallback value in case any values are not present when parsing a Templ8 instance. Default is "", Empty String.
idThe ID of your Templ8. This is handy (and mandatory) if you want to use a Templ8 from within another Templ8. Otherwise an anonymous ID will be generated for your Templ8.
logCompiledTplUseful for debugging. Set this to true to have the Templ8 method body logged to the console. Default is false.

 

Templ8 instance methods

To keep it simple, a Templ8 instance only contains one method.

parse( dictionary:Object ):String

This method accepts one parameter: an Object of values you want to substitute and returns a String of the parsed Templ8.

Any tokens in the Templ8 that do not have a dictionary value will use the fallback value described above,


 

Templ8 variables

basic global variables
$_

This is based on perl's $_ and is a reference to the the current dictionary value being parsed.

For instance if you are in a loop, rather than access the value using iter.current you could also access it via $_.

e.g. instead of this:

    {[ iter.current|parse:'sub_template' for each ( items ) ]}

or this:

    {[ item|parse:'sub_template' for each ( item in items ) ]}

you could do this:

    {[ $_|parse:'sub_template' for each ( items ) ]}
iter

This is the current iterator being parsed. It is an instance of an internal class called Iter. Iter instances are created internally, when you use a {% for %} loop or an Array Comprehension {[ for each ]} tag you should not need to create one yourself.

It has the following properties available for both Arrays and Objects:

countthe total number of all items in the Array or Object
currentThe current item being iterated over.
firstThe first item in the Array/ Object. Note: you cannot guarantee iteration order in an Object.
indexThe zero based index of the curent iteration.
index1The one based index of thecurrent iteration.
lastThe last item in the Array/ Object.
nextThe next item in the iteration, or undefined if we're at the last item.
parentIf you are in a nested loop and want to call the parent iter, you can access it via this property.
previousThe previous item in the iteration, or undefined if we're at the first item.

It has the following extra properties available for Objects:

firstKeyThe key of the first item in the Object.
lastKeyThe key of the last item in the Object.
keyThe key of the current item being iterated over in the Object.
nextKeyThe next key in the iteration, or undefined if we're at the last item.
previousKeyThe previous key in the iteration, or undefined if we're at the first item.

It also has the following two methods:

hasNextreturns true if there is a value after the current iteration to iterate over. Otherwise it will return false.
stopwill stop the iterating, once it finishes it's current iteration.

 

Templ8 internal variables

Along with the above Templ8 has some internal variables accessible for the more advanced user, should they require access to them.

$C or __CONTEXT__

Templ8 does not use the JavaScript with statement. It implements its own version of a with statement using an internal class called ContextStack.

It has five methods (you should NOT call these if you DO NOT know what you're doing):

currentreturns the current context Object
destroydestroys the ContextStack.
getattempts to return the value of a dictionary Object, if it is in the ContextStack, otherwise it will return the fallback value or undefined.
popremoves the most recently added dictionary Object from the ContextStack.
pushadds a dictionary Object to the ContextStack.
__OUTPUT__

This is where all parsed template output is stored. It is an instance of an internal class call Output.

It has two methods:

joinreturns the output of the Templ8 instance.
pushadds a String representation of the passed parameter to the Templ8 instance's output.
__ASSERT__

This is a reference to Templ8.Assertions.

__FORMAT__

This is a reference to Templ8.Filters.

__UTIL__

This is a reference to the internal utility functions used by Templ8.


 

Tags


 

Statements

Examples (by tag)

Tag: {{}}

Replacing values
    var tpl = new Templ8( '{{value}}' );

    tpl.parse( { value : 'github.com' } ); // returns: *github.com*
Filtering values
    var tpl = new Templ8( '{{value|truncate:30|bold|link:"http://github.com"}}' );

    tpl.parse( { value : 'github.com is great for sharing your code with other people.' } ); 

returns the String:

	<a href="http://github.com"><strong>github.com is great for sharin...</strong></a>
One line if statement
    var tpl = new Templ8( '{{value if value|notEmpty}}' );
    
    tpl.parse( { value : 'github.com' } ); // returns: *github.com*

    tpl.parse( {} );                       // returns: empty String ( "" )
One line unless statement
   var tpl = new Templ8( '{{value unless value|equals:"foo"}}' );

    tpl.parse( { value : 'github.com' } ); // returns: *github.com*

    tpl.parse( { value : 'foo' } );        // returns: empty String ( "" )

 

Tag {%%}

conditions: if|unless/ elseif/ else/ endif
    var tpl = new Templ8(
        '{% if value == "foo" || value == "bar" %}',
            '{{value}}',
        '{% elseif value != "lorem ipsum" %}',
            '{{value|bold}}',
        '{% elseif value|notEmpty %}',
            '{{value|italics}}',
        '{% else %}',
            'No value',
        '{% endif %}'
    );

    tpl.parse( { value : 'foo' } );            // returns: foo

    tpl.parse( { value : 'lorem ipsum' } );    // returns: <strong>lorem ipsum</strong>

    tpl.parse( { value : 'dolor sit amet' } ); // returns: <em>dolor sit amet</em>

    tpl.parse( {} );                           // returns: No Value
iterating: for/ forempty/ endfor
    var tpl = new Templ8(
	    '{% for item in items %}',
            '{{item}}',
        '{% forempty %}',
            'No items',
        '{% endfor %}' 
    );
sub/ endsub templates
    var tpl = new Templ8(
        '{% sub sub_template_name %}',
            '{{$_}}',
        '{% endsub %}' 
    );

 

Tag {[]} (Array comprehensions or one line for loops)

    var tpl = new Templ8( '{[ v|parse"k" for each ( [k,v] in items ) if ( k|isTPL ) ]}' );

 

Tag {::}

Allows you to execute arbitrary JavaScript.

    var tpl = new Templ8( '{: aribtrarily.executing.nasty.code.isFun(); :}' );

 

Tag {##}

Allows you to add comments in your template.

    var tpl = new Templ8( '{# doing something complex and describing it is sensible, but not probable #}' );

License

(The MIT License)

Copyright © 2011 christos "constantology" constandinou http://muigui.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 14 Jul 2011

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc