Is it possible to assign a parameter value within handlebars templates without using helpers?

泪湿孤枕 提交于 2020-05-25 05:45:32

问题


I am trying to assign values within a template, the idea is to do something like this:

    {{#if author}}
        {{className = 'classA'}}  <- trying to implement this line.
    {{else}}
        {{className = 'classB'}}
    {{/if}}

<div class={{className}}></div>

Is it possible to do so without registerHelper?


回答1:


You can do this with a partial.

partial:

<div class="{{classname}}">{{var1.author}}</div>

template:

{{#if author}}
{{> mypartial var1=. classname="classA"}}
{{else}}
{{> mypartial var1=. classname="classB"}}
{{/if}}

In this example I've passed the current scope as var1. I can't recall if the scope stays the same and the new variable is just added to it or if you have to pass the scope manually.




回答2:


I needed this solution solved in the same way the original poster expected. Therefore I created a helper function to do this for me.

function setVariable(varName, varValue, options){
  options.data.root[varName] = varValue;
};

Contained within the options in the helper, is the data block, with the root of the helper variables.

I placed my variable within the root object, either assigning or overwriting with the value provided.

The helper in html looks a lot like this.

{{setVariable "thisVar" "Contents Here"}}

<div>
  {{thisVar}}
</div>



回答3:


Small update from a helpful above answer. In Handlebars 4.x, it seems we have to get the variables from @root.

handlebars.registerHelper('assign', function (varName, varValue, options) {
    if (!options.data.root) {
        options.data.root = {};
    }
    options.data.root[varName] = varValue;
});

And then,

{{assign 'imageTag' 'drop-155'}}

{{@root.imageTag}}



回答4:


 {{#if author}}
       <div class='{{ classA }}'></div>
    {{else}}
        <div class='{{ classB }}'></div>
    {{/if}}

or try

<div class='{{#if author}} {{ classA }} {{else}} {{ classB }} {{/if}}'></div>

or maybe this

create a script

<script> 
  $(function(){
       var class;
       {{#if author}}
          class = {{ classA }}
       {{else}}
          class = {{ classB }}
       {{/if}}

   var $specials = $('.special');
   $specials.removeClass('special');
   $specials.addClass(class);
  })

</script>


来源:https://stackoverflow.com/questions/24736938/is-it-possible-to-assign-a-parameter-value-within-handlebars-templates-without-u

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!