JsRender …. starter for 10

I was going to look at jQuery Templates recently, but then I discovered they have been discontinued. Which is a real pity as I saw a demonstration at a conference about a year ago and they looked rather promising. However, there are other similar projects out there that do similar things. So instead, I’m going to look at JsRender and JsViews.

At the moment there is very little documenation out there for either JsRender or JsViews, so this is some of the bits I’ve been able to piece together. Some of the simpler demos actually only use JsRender. And, of course, at this stage the project is still pre-beta so some of this may change.

To get going you need to add a reference to the JsRender javascript library. You can find that on github. Although you don’t need jQuery for JsRender, it can take advantage of jQuery to make some things easier. I’ll be showing JsRender with jQuery as I happen to think it makes things easier.

Hello World!

To start with the template is rendered in a script block with a type of “text/x-jsrender”. The templated parts themselves are made up of two sets of braces with an expression inside. For example:

<script id="helloTemplate" type="text/x-jsrender">
  <p>Hello, {{:name}}!</p>

Next, we need some javascript to wire up the template with some data

<script type="text/javascript">
    // Set up the data
    var thePerson = { name: "Colin" };

    // Render the template to a string
    var renderedHtml = $("#helloTemplate").render(thePerson);

    // insert the rendered template into an existing element
    // In this case it is a span.

To see the example in action, click here and view the source of the page to see the underlying code.

1 Comment

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s