1

How do you handle templating HTML and JSON without locking the HTML into javascript strings?

I have an ajax-enabled site that presents a lot of dynamic content by interpolating JSON values with HTML. This all works fine.

BUT it means I have significant amounts of HTML all through my JavaScript. For example:

var template = "<div>Foo: {bar}</div><div>Blah: {vtha}</div>";          
template.interpolate({bar:"bar",blah:"vtha"});      

I have cut this down a fair bit - some of my dynamic elements have quite a lot of HTML and a lot going on.

I am using jQuery and I am building on Rails, so if there is something smart in either framework, that would be great.

For reference, the String interpolation function used above is:

String.prototype.interpolate = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
          var r = o[b];
          return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};
4
  • So... what's the question? Are you asking how to do this without locking the HTML into javascript strings? Commented Apr 19, 2010 at 13:58
  • 1
    That interpolation is a potential security problem. Because it's not HTML-escaping text strings, any untrusted input you end up putting on the page can inject markup (including JavaScript) into your page's security context. You have made a client-side XSS risk. Commented Apr 19, 2010 at 14:14
  • @peter: well put, much more succinct than my q. Commented Apr 19, 2010 at 23:37
  • @bobince: No risk here, the data is all trusted. Commented Apr 19, 2010 at 23:38

3 Answers 3

1

I would definitely use the approach "Load when needed".

Build small widget that you can load with ajax that's complete with html, data and so on. Use jquery's load function.

$('#wrapper').load('/widgets/foobar/')

And have the server create all your elements you need. It will be some more loading of data for each widget. But you don't have to create them on client side. I would say the pro out weight the cons in this. Since it will be easier for the client just to add already parsed html instead of building it up in javascrtipt.

Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried using Distal templates that allows you to define the template as HTML.

Comments

0

If you want to keep the HTML template code in the HTML and out of the JavaScript then just do something like this.

Javascript:

$(document).ready(function() { var template = $('#template-example').html(); template.interpolate({bar:"bar",blah:"vtha"}); });

HTML:

<div id="template-example" style="display:none;"> <div>Foo: {bar}</div><div>Blah: {vtha}</div> </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.