donquixote
donquixote

Reputation: 5491

handlebars: "capture" a piece of html into a variable

Here is what i'd like to do within a handlebars template:

{{#capture $str}}racing car{{/capture}}
i want a {{$str}} for xmas!

Intended outcome:

i want a racing car for xmas!

So, the captured/recorded html should be written to a local variable which can then be printed.

Any ideas?


EDIT: Use case
Ok, at first I just want to know if this is possible. I might try it and then do something else.

Still, here is a more elaborate use case. Still it is made-up, but seeing the exact thing won't add much value.

{{#capture $long_html_1}}
  <input class=".." name=".." value=".." />
{{/capture}}

{{#capture $long_html_2}}
  <select class=".." name="..">
    <option ... />
    <option ... />
    <option ... />
    <option ... />
  </select>
{{/capture}}

{{#if layoutVariation1}}
  <section class="layout-1">
    <div class="row-fluid">
      <div class="span5">{{$long_html_1}}</div>
      <div class="span7">{{$long_html_2}}</div>
    </div>
  </section>
{{else}}
  <fieldset class="whatever-something-else">
    <label ...>The label</label>
    <div class="box">{{$long_html_1}}</div>
    <div class="box">{{$long_html_2}}</div>
  </fieldset>
{{/if}}

I don't want to repeat the declaration of the two $long_html_X elements. I also don't want to make a separate template for each of them (or maybe I should?). And I want to reduce the amount of if/else handlebars tags, to keep it readable.

Upvotes: 0

Views: 1259

Answers (1)

Emre Efendi
Emre Efendi

Reputation: 2587

You can use "handlebars partials" like variables.

Partial templates

<script id="long_html_1" type="text/x-handlebars-template">
  <input class=".." name=".." value=".." />
</script>

<script id="long_html_2" type="text/x-handlebars-template">
  <select class=".." name="..">
    <option ... />
    <option ... />
    <option ... />
    <option ... />
  </select>
</script>

Main template

<script id="main" type="text/x-handlebars-template">
{{#if layoutVariation1}}
  <section class="layout-1">
    <div class="row-fluid">
      <div class="span5">{{> long_html_1}}</div>
      <div class="span7">{{> long_html_2}}</div>
    </div>
  </section>
  {{else}}
  <fieldset class="whatever-something-else">
    <label ...>The label</label>
    <div class="box">{{> long_html_1}}</div>
    <div class="box">{{> long_html_2}}</div>
  </fieldset>
{{/if}}
</script>

Rendering script

var template = Handlebars.compile($("#main").html());

Handlebars.registerPartial("long_html_1", $("#long_html_1").html());
Handlebars.registerPartial("long_html_2", $("#long_html_2").html());

var html1 = template({layoutVariation1: true});
var html2 = template({layoutVariation1: false});

$(document.body).html(html1 + '<hr>' + html2);

​You can check out a working example at http://jsfiddle.net/nUDf3/

Upvotes: 1

Related Questions