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?
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') }}">
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