The Lens Templating System
Lens uses the templating system from Meteor. Documentation on how to construct templates and bind events inside templates can be found in the Meteor templates documentation and the Meteor UI API.
Lens scans the templates
folder at the root of your app for files ending in
.html
. These are parsed in the same way as Meteor templates, except that
head
and body
sections are ignored (so only template
blocks are used). The
templates are available under the Lens.Template
namespace. If you'd like Lens
to scan a different folder, set the templates_folder
in your app.json file
(this value defaults to "templates"
). You can even set template_folder
to
.
, which will cause Lens to scan your entire app for .html
files (except
for index.html
, which is ignored for the purposes of templating).
If Lens encounters an error while parsing your templates, you'll see that error in the browser console when running your app.
Inserting Templates
To insert a template into your page, you first render it with Lens.UI.render
.
Then, you insert it into the page with Lens.UI.insert
.
var rendered = Lens.UI.render(Lens.Template.foo_template);
// plain DOM:
UI.insert(rendered, document.body);
// jQuery:
UI.insert(rendered, $("body")[0]);
Reactivity
Templates are rendered inside a Lens.Deps
.autorun block, so the DOM
elements returned by render
are live-updated as the underlying data changes.
See Reactivity for a detailed explaination of how this works and
what data sources are supported.
Here's an example of using a template to show a user's score. First, here's
templates/score.html
:
⟨template name="score"⟩
Player score: {{player_score}}
⟨/template⟩
And here's how we use it in Javascript:
// tell the template what to insert in place of {{player_score}}
Lens.Template.score.player_score = function() {
return Lens.Session.get("score");
}
var rendered = Lens.UI.render(Lens.Template.score);
UI.insert(rendered, document.body);
Now, when we set the player's score with Lens.Session.set("score", newScore)
,
the template will be automatically re-rendered and the page will update.
We can use the same technique to live-update the app with data from a
Lens.DB
or Machine
.