I'm trying to learn about new usages of javascript as a serverside language and as a functional language. Few days ago I heard about node.js and express framework. Then I saw about underscore.js as a set of utility functions. I saw this question on stackoverflow . It says we can use underscore.js as a template engine. anybody know good tutorials about how to use underscore.js for templating, especially for biginners who have less experience with advanced javascript. Thanks
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
I am giving a very simple example
1)
The result would be
2) This is a template
This is html
This is the javascript code which contains json object and putting template into html
with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :
then you should change the default engine to html template by this:
register the underscore template engine for the html extension:
it's done !
Now for load for example an template called 'index.html':
I hope this helped you!
Lodash is also the same First write a script as follows:
Now write some simple JS as follows:
Where popoup is a div where you want to generate the table
Everything you need to know about underscore template is here. Only 3 things to keep in mind:
<% %>
- to execute some code<%= %>
- to print some value in template<%- %>
- to print some values HTML escapedThat's all about it.
Simple example:
then
tpl({foo: "blahblah"})
would be rendered to the string<h1>Some text: blahblah</h1>
In it's simplest form you would use it like:
If you're going to be using a template a few times you'll want to compile it so it's faster:
I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:
I wanted to share one more important finding.
use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.
We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance