Search code examples
twig

Formatting statements


Currently I'm using this:

{% if locale == 'pt' %}
<html lang="pt-BR">
{% elseif locale == 'en' %}
<html lang="en-US">
{% endif %}

It's decent, but makes the whole <html> tag repeat in the source code. What do you think?

In PHP templates I often use this:

<html lang="<?php
if ($locale === 'pt') {
    echo 'pt-BR';
} elseif ($locale === 'en') {
    echo 'en-US';
}
?>">

I was wondering if there's a way to produce a similar result with Twig. This is the best I got so far, but it looks a bit odd to me:

<html lang="{%
if locale == 'en'
%}en-US{%
elseif locale == 'pt'
%}pt-BR{%
endif %}"></html>

Is there a neater way to do this?

https://twigfiddle.com/4lwsjb


Solution

  • You could create an array/hash to shorten your code:

    {% set localization = {
        'pt': 'pt-BR',
        'en': 'en-US',
    } %}
    <html lang="{{ localization[locale]|default('en-US') }}">
    

    demo


    I would even suggest to just create the localization array in your controller and pass it to the view or register it as a global variable

    The default filter I've just added to provide a fallback if the locale is unknown in the array