Skip to content
This repository has been archived by the owner on Mar 21, 2019. It is now read-only.
/ tiny-template Public archive

A tiny template engine without using `eval` or `new Function`

License

Notifications You must be signed in to change notification settings

yuanchuan/tiny-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Tiny-template

A tiny template engine without using eval or new Function, but with limited feature support. Used for situations where the Javascript execution environment is restricted like in the Google-chrome-extension apps.

Installation

Install from npm:

npm install tiny-template

Or through component:

component install yuanchuan/tiny-template

Syntax

The interpolate tags are similar to the default settings of Underscore templates:

<% ... %> begins the code statement

<%= .. %> indicates the variable

<% end %> ends the code statment

Supported code statement

1. each

<ul>
  <% each (array, el, i) %>
    <li> <%= el %>, <%= i %><li>
  <% end %>
</ul>

2. if

<% if (bool) %>
  <p>hello<p>
<% end %>

API

.parse(string)

Given the template string:

<% each (array, el, i) %>
  <span><%= el %>, <%= i %></span>
<% end %>

Will output:

{
  "block": [
    {
      "operator": {
        "name": "each",
        "data": "array",
        "args": [ "el", "i" ]
      },
      "block": [
        {
          "text": "\n  <span>"
        },
        {
          "variable": "el"
        },
        {
          "text": ", "
        },
        {
          "variable": "i"
        },
        {
          "text": "</span>\n"
        }
      ]
    }
  ]
}

.compile(string, dataObj)

Given the template string

<% each (array, el, i) %>
  <span><%= el %>, <%= i %></span>
<% end %>

And the dataObj

{
  array: ['a', 'b', 'c']
}

Will output

<span>a, 0</span>
<span>b, 1</span>
<span>c, 2</span>

TODO

  • support object traverse in each
  • support object scope variables like obj.something
  • support custom interpolate tags
  • support common comparison in if like if ( a == 1 )
  • exeption handling

License

MIT

About

A tiny template engine without using `eval` or `new Function`

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published