How can i use string interpolation with Jekyll?

I have a Jekyll 3 project that allows language selection. We use the 'jekyll-multiple-languages-plugin' gem for internationalization. We have a glossary that is supposed to display German terms or English terms according to the selected language. I get the selected language using the variable site.lang provided by the 'jekyll-multiple-languages-plugin' gem. Right now glossary.html looks like this

  <div id="glossary">
    {% if site.lang == "de" %}
      {% for term in site.data['terms_de'] %}
        <!-- German glossary goes here -->
      {% endfor %}
    {% elsif site.lang == "en" %}
      {% for term in site.data['terms_en'] %}
        <!-- English glossary goes here -->
      {% endfor %}
    {% endif %}
  </div>

However, i'd love to have something like this

  <div id="glossary">
     {% for term in site.data["terms_#{site.lang}"] %}
       <!-- Glossary goes here -->
     {% endfor %}
  </div>

But for some reason, the string interpolation "terms_#{site.lang}" doesn't work. I also tried 'terms_'+site.lang

I think the interpolation is not working because, when i put {{ site.lang }} in the page, i see the selected language, but when i write {{ "terms_"+site.lang }} i don't see anything.

Thanks in advance.

Upvotes: 2

Views: 1184

Answers (1)

marcanuy
marcanuy

Reputation: 23982

You can make use of the capture tag, instead of displaying a value it sets to a variable:

{% capture term_lang %}{{ 'terms_' | append: site.lang }}{% endcapture%}

Then you can use that variable as the index of the array:

 site.data[term_lang]

In your example:

{% capture term_lang %}{{ 'terms_' | append: site.lang }}{% endcapture%}
<div id="glossary">
 {% for term in site.data[term_lang] %}
   <!-- Glossary goes here -->
 {% endfor %}
</div>

Upvotes: 4

Related Questions