Using ERB with Handlebars templates

2019-07-02 08:27发布

问题:

I have a modal that makes new tags with ajax. It does a POST method with the Tags parameters without recharging the view. So I want, depending on the "price_type" parameter chosen, to render one price div or another. Im using Handlebars so I suppose this is not ruby's conditional responsability (because of AJAX), but Handlebars conditionals responsability.

The problem is I tried plenty of ways of making Handlebars conditionals with no success.

I want to achieve the equivalent of this with Handlebars conditionals, where @tag.price_type is stored as {{price_type}} in JS. Since I'm using AJAX, if I try this it wont work.

    <script id="entry-template" type="text/x-handlebars-template">
      <% if @tag.price_type === 1 %>
        <span class="small right white article_price">{{min_price}} €</span>
      <% elsif @tag.price_type === 2 %>
        <span class="small right white article_price">{{min_price}} €</span> - <span class="small right white article_price">{{max_price}} €</span>
      <% else %>
        <span class="small right white article_price">No sabe</span>
      <% end %>
    </script>

Is it possible? Maybe saving the file as hbs.erb? If not, how would the pure Handlebars template be? I tried making a custom Helper which I didn't understand, but nothing. Thank you guys.

回答1:

You need to name your file something with .hbs.erb at the end of it, rather than simply .hbs .

This will encourage Rails to compile the file first as an .erb file (injecting erb data into the .hbs file), then Rails will render the file as a .hbs (Rails compiles files in the order of file extensions from right to left).