Search code examples
javascripthtmlgulpinternationalizationrendering

Gulp, Moustache. How to concat data with src attribute?


I'm using the gulp-html-i18n gulp plugin for handling the translations task in a static website.

In order to display the translated content, I should use the Moustache lib as gulp-html-i18n mentioned in his doc.

I'm facing difficulties in the concatenation operations. For example, if I need to assign a conditional class for a html element, I will use the following flow:

${{! if}}$
 ${{#index.isEnglish}}$
<body class="en">
 ${{/index.isEnglish}}$
${{! else}}$
 ${{^index.isEnglish}}$
<body class="sp">
 ${{/index.isEnglish}}$

In the code above, I'm checking if the language is English, for example, then the class is assigned based on the isEnglish value.

By this approach, we will face a big problem if I need to add new language also it's long and not comprehensive.

Moreover, let suppose I have an array of objects in the following interface:

"data":[{
 "title": "foo",
 "description": "bar",
 "icon": "iconname"
},...]  

What if I need to concat the icon name with the scr attribute path while looping through the array above?

<div class="content">
    ${{#index.home.services.data}}$
    <h3>
        ${{title}}$
    </h3>
    <p>
        ${{description}}$
    </p>
    <img src="path/${{}}$.png" alt=""> ---> Not working with Moustache
    ${{/index.home.services.data}}$
</div>

So how can I solve the problems above? and what is the best practices for the Moustache.js concatenations?


Solution

  • Sloved!

    Solved by using scripts of type text/template.

    We can't do the concatition operator directly inside a html attribute, We should write it inside a script of type text/template. like the following example:

    <script type="text/template" id="header">
        ${{#index.pages}}$
        <button>
            <a href="./${{fileName}}$"></a>
            ${{title}}$
        </button>
        ${{/index.pages}}$
    </script>
    

    Then render the script content and assign it to specific html element using the following javascript code:

    var headerTemplate = $('#header').html();
    var headerHtml = Mustache.to_html(headerTemplate);
    $('#navBar').html(headerHtml);
    

    Note: The dollar signs are used based on gulp plugin for localization task gulp-html-i18n in order to link the json file to mustache.

    If I'm not using the mentioned plugin I must update my code to become:

    var headerTemplate = $('#header').html();
    var headerHtml = Mustache.to_html(headerTemplate,'path to data');
    $('#navBar').html(headerHtml);
    

    One of the most helpful link here.