Lodash Templates

We can improve our front end using templates. Templates are strings, potentially take from the DOM, which can be compiled against an object to produce a new DOM node

LoDash (a fast implementation of underscore) provides one such implementation.

First we must include loDash on our page using a script tag: https://lodash.com

Then we create a template as a string and compile it against an object

var template = _.template("Hello {{ name }}!");
var compiledTemplate = template({name: "World"});
// Outputs: "Hello World"

Pulling the template from the DOM

We don't want to be writing templates as strings in our JavaScript. Ideally we compose HTML in our HTML. The most convenient way to do this is with a script tag.

We set a type of text/template to prevent the browser from trying to execute the template as JavaScript. We set an id attribute to allow us to find the template.

<script type="text/template" id="helloTemplate">
"Hello {{ name }}!"
</script>

We can then write some JavaScript:

$(function() {
var templateStr = $('#helloTemplate').html();
var template = _.template(templateStr);
var compiledTemplate = template({name: "World"});
})

Exercise - Mario

Extract your Mario UI into a template.

Harder Exercise - A Flickr feed

Improve your Flickr app.

Create a template which renders a single image from the feed, now use lodash to pull this template from the DOM and, for each image, render the image and draw it to the DOM.

Do you like Email? Do You Like JavaScript?

Sign up for occasional emails covering modern Web Development topics such as Angular 2 and React. You can unsubscribe at any time.

We totally respect your email privacy

comments powered by Disqus