handlebars.js - Define object & pass it to a partial -


what want do:

{{>mypartial foo={bar:1} }} 

i want define object while passing partial. possible?


i know it's possible pass existing object like

{{>mypartial foo=foo}} 

but want define object within markup.

why? because it's define layout. want avoid determine layout decisions on backend.
partial table layout, , want hide specific columns.

but instead of using multiple properties like

{{>mypartial hidefoo=true hidebar=true}} 

i want use single object hide

{{>mypartial hide={foo:true,bar:true} }} 

you can pass new context partial:

{{> mypartial context }} 

example:

var data = {   title: "foo bar",     foo: ["foo1", "foo2"],     bar: ["bar1", "bar2"],     hide: {         foo: true,         bar: false     } };  var content = "{{title}} {{> mypartial hide }}"; var partialcontent = "<div class=\"{{#if foo}}hidefoo{{/if}} {{#if bar}}hidebar{{/if}}\">hide</div>"; var template = handlebars.compile(content); handlebars.registerpartial("foo", partialcontent); template(data); 

output:

<div class="hidefoo hidebar">hide</div> 

another way pass json string, instead of object, using helper in way:

//helper handlebars.registerhelper("parsejson", function(string, options) {   return options.fn(json.parse(string)); });  //template     {{#parsejson '{"foo": true,"bar": true}'}}      {{> mypartial}} {{/parsejson}} 

demo:

//compile main template  var template = handlebars.compile($("#template").html());    //register partial  handlebars.registerpartial("mypartial", $("#mypartial").html());    //register parsejson helper  handlebars.registerhelper("parsejson", function(string, options) {    return options.fn(json.parse(string));  });    //your data  var data = {    title: "foo bar"  };      document.body.innerhtml = template(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>  <!-- template.html -->  <script id="template" type="text/x-handlebars-template">    <h1>{{title}}</h1>        <h3>first partial:</h3>    {{#parsejson '{"foo": true,"bar": false}'}}        {{> mypartial}}    {{/parsejson}}        <h3>second partial:</h3>     {{#parsejson '{"foo": false,"bar": false}'}}        {{> mypartial}}    {{/parsejson}}  </script>    <script id="mypartial" type="text/x-handlebars-template">    <div>hide.foo: {{foo}}</div>    <div>hide.bar: {{bar}}</div>  </script>


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -