underscore icon indicating copy to clipboard operation
underscore copied to clipboard

Embed precompiled template to a template

Open cardinal27513 opened this issue 13 years ago • 4 comments

Hi, we've a need to break template into small pieces. We added the following 'embed' addition to template:

<%# embed_template %>

Here is how it can be used:

<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript"  src="underscore.js"></script>
    <script type="text/javascript" >
        var _best_tmpl      = _.template ("<p>This is the best.</p>");
        var _better_tmpl    = function (data) {
            var _tmp = _.template ("<p>This is better.</p> <%# best_tmpl %> ");
            return _tmp (data);
        }
        var _good_tmpl      = _.template ("<p>This is good.</p> <%# better_tmpl %> ");

        var _tmpl_1 = _good_tmpl ({better_tmpl: _better_tmpl, best_tmpl: _best_tmpl});
        document.write (_tmpl_1);
    </script>
    </head>
    <body>
    </body>
</html>

The change is very straight forward,

      if (embed) {
        source += "'+\n((__t=(" + embed + "(" +  (settings.variable || 'obj') + ")))==null?'':__t)+\n'";
      }

If there is an interest, I can create a pull request.

Thanks,

cardinal27513 avatar Mar 09 '13 21:03 cardinal27513

There are a few things that I don't like about this approach. It relies on an unstated convention that a cited variable with an extra underscore is your precompiled template.

Also, a precompiled template is just a function. Why not just call the function with the existing <%= %> syntax?

bjmiller avatar Mar 09 '13 21:03 bjmiller

I started from there and used <%= tmpl (obj) %>. It works but then realized that I need to assume 'obj' to be passed into my next pre-compiled template. That becomes cumbersome to alway adding that in the template

With what is suggested, it takes away the need to specify 'obj' and underscore will take care of it. Thinking that this is a super 'light-weight sub-template' mechanism. It gives a pretty simple-way to embed template out-of-the-box without complicated implementation.

This becomes handy when using with templateHelpers in backbone.marionette

cardinal27513 avatar Mar 10 '13 00:03 cardinal27513

HI @cardinal27513! Thanks for bringing this up. As @bjmiller points out, however, templates are just functions and using <%= template(obj) %> is simple and easily understood. I've written things like this in the past and always wished that I'd stuck with plain old functions. I often call templates with a context, which cuts down on boilerplate without introducing new syntax.

var view = {
  name: 'foo',
  template: _.template('<div><%= this.subTemplate() %></div>'),
  subTemplate: _.template('<p><%= this.bodyTemplate() %></p>'),
  bodyTemplate: _.template('<%- this.name %>')
};
view.template(); // <div><p>foo</p></div>

braddunbar avatar Mar 10 '13 13:03 braddunbar

Thanks!

cardinal27513 avatar Mar 10 '13 17:03 cardinal27513