Require with Hogan and how to render html entity from JSON
Asked Answered
P

1

5

I am using Hogan js for my template and require js as a module loader. Have the necessary libraries such as jquery js, hogan js, require js in place.

index.html is below

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>RequireJS - AMD</title>
    <script data-main="main" src="require.js"></script>

    <!-- Template -->
    <script id="tmpl-heading" type="text">
        <h3>{{heading}}</h3>
        <p>{{article}}</p>
    </script>
</head>
<body>
</head>
<body>
    <div id="heading"></div>
</body>
</html>

and main js is below,

require(['jquery', 'hogan'], function($, hogan){
        var headingData = {
            heading: "Some heading goes here",
            article: "<a href='http://www.lipsum.com'>Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit. Donec varius, velit pulvinar sollicitudin auctor, nibh nibh mattis diam, vel elementum tortor urna ac diam. Sed tellus neque, gravida nec facilisis et, pellentesque quis enim."
        };

        var hSource = $("#tmpl-heading").html();

        var hTemplate = Hogan.compile(hSource);

        var hData = hTemplate.render(headingData);

        $("#heading").html(hData);

        //$("#heading").html(headingData.article);
});

My issue: on the browser the text within the anchor tag is not rendered as link and rendered as text.

however, if I don't use hogan and so something like below, the result is as expected. Link is rendered correctly.

require(['jquery', 'hogan'], function($, hogan){
        var headingData = {
            heading: "Some heading goes here",
            article: "<a href='http://www.lipsum.com'>Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit. Donec varius, velit pulvinar sollicitudin auctor, nibh nibh mattis diam, vel elementum tortor urna ac diam. Sed tellus neque, gravida nec facilisis et, pellentesque quis enim."
        };

       $("#heading").html(headingData.article);
});

please point me towards the necessary changes needs to be done while using Hogan (I'm sure i must have missed some important bit however unable to figure out) and i should be able to render anchor on front end as link. Thanks in advance.

Pontus answered 10/12, 2012 at 11:58 Comment(3)
Use triple mustaches for the parts you wish to be rendered as html. In your case it would be <p>{{{article}}}</p> instead of <p>{{article}}</p>.Zymogenic
wow, Thanks N.B. I completely forgotten this simple solution from Mustache.Pontus
No problems, have fun with Hogan :)Zymogenic
P
7

Use tripple curly braces if you want to output html. {{{html}}}

from the docs:

All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: {{{name}}}.

You can also use & to unescape a specific variable.

https://github.com/janl/mustache.js/

Pulpiteer answered 3/7, 2015 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.