Meules Meules - 3 years ago 214
Twig Question

Twig check if there are duplicates

I'm fairly new to Twig. I'm creating a template where users can set a Google font-family in. They set those font-families for three different options.

Body text
Headings
Navigation

The selected values are loaded in the template like:

<link href='//fonts.googleapis.com/css?family={{ theme.headings_google_webfonts | url_encode }}:400,300,600,800' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family={{ theme.body_google_webfonts | url_encode }}:400,300,600,800' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family={{ theme.navigation_google_webfonts | url_encode }}:400,300,600,800' rel='stylesheet' type='text/css'>


Now when people select the same font for all options the template would load the font three times which is absolutely unessesary.

How can you make a rule or test that checks if the same font value is already present and if so don't load it??

I thought something in the lines of this would work, but this obviously doesn't work:

{% set fonts = theme.body_google_webfonts in [theme.navigation_google_webfonts, theme.navigation_google_webfonts] ? ...... %}

Answer Source

Keep a record of what you have already included in an array:

<link href='//fonts.googleapis.com/css?family={{ theme.headings_google_webfonts | url_encode }}:400,300,600,800' rel='stylesheet' type='text/css'>
{% set fonts_done = [ theme.headings_google_webfonts ] %}
{% if theme.body_google_webfonts not in fonts_done %}
    <link href='//fonts.googleapis.com/css?family={{ theme.body_google_webfonts | url_encode }}:400,300,600,800' rel='stylesheet' type='text/css'>
    {% set fonts_done = fonts_done|merge([ theme.body_google_webfonts ]) %}
{% endif %}
{% if theme.navigation_google_webfonts not in fonts_done %}
    <link href='//fonts.googleapis.com/css?family={{ theme.navigation_google_webfonts | url_encode }}:400,300,600,800' rel='stylesheet' type='text/css'>
    {% set fonts_done = fonts_done|merge([ theme.navigation_google_webfonts ]) %}
{% endif %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download