Create link in handlebars.js using helper

心不动则不痛 提交于 2019-12-12 02:57:18

问题


I have tried to follow the example in the handlebars documentation on how to create a link, but the instructions are very unclear to me. handlebarsjs.com/expressions.html (see "Helpers")

First of all, without the link helper I can make the link text appear on the screen, but just as text, not a link.

<script id="template" type="text/x-handlebars-template">
          <h4>{{{my_link}}}</h4>
 </script>

And the text is retrieved from an ajax request. Then I add the link keyword

<h4>{{{link my_link}}}</h4>

And then nothing is displayed. This is the helper code I have currently, which doesn't work:

$(function(){
    Handlebars.registerHelper('link', function(my_link) {

        var url = Handlebars.escapeExpression(my_link.url);
        var result = "<a href='" + url + "'></a>";
        console.log(result);

        return new Handlebars.SafeString(result);

    });
});

Is it relevant where I put this piece of code in the javascript?

When I click a submit button, the ajax request is made and the link is retrieved. With the link helper, the console.log gives an empty link:

"<a href=''></a>"

回答1:


Since you registered the name of the helper as link, your template should start with {{{link

So

<h4>{{{my_link}}}</h4>

should be

<h4>{{{link my_link}}}</h4>

And

var url = Handlebars.escapeExpression(my_link.url);

should be changed to

var url = Handlebars.escapeExpression(my_link);




回答2:


Instead of creating the whole a element I can suggest you to create helper for attribute only. This way you can reuse it to many others elements and also the code will be much simpler and better to read in the templates. For example I have build this attr helper function:

handlebars.registerHelper('attr', function(name, data) {
    if(typeof target === 'undefined') target = "";

    var result = ' ' + name + '="' + data +  '" ';

    return new handlebars.SafeString(result);
});

And here is how it looks in the template:

<a target="_blank" {{attr 'href' general.link}}><img src="assets/images/nice_image.png" class="link-icon" /></a>

I think this approach is much more simpler, and even more reusable than having helper to create the whole element. You can name the helper in the way that will match the attribute also, href, src...



来源:https://stackoverflow.com/questions/31173154/create-link-in-handlebars-js-using-helper

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