Cheking if translation exists

Is there a way - in Twig - to check if a specific translation exists in the currently active language (html_lang)?

I tried something like this

{% if 'STRING.TRANSLATION.PATH' %}
//do stuff
{% endif %}

But that always equals true, apparently.

Setting translations_fallback to false doesn’t help.

There may be a simpler way I don’t know, but …

What do you get from the t custom Twig filter (translate string to current language)? What do you get for a result if you output {{ 'MY_STRING'|t }}. If it’s empty or undefined, you should be able to simply put an if in front of it, do if .. is defined, if .. is not empty etc.

TLDR: Based on some tests I noticed the following

  • Is language supported: html_lang in config.system.languages.supported
  • Is translation available: html_lang == grav.language.getLanguage
  • Does string have translation: 'TRANSLATE_ME'|t != 'TRANSLATE_ME'

Created a site with the following settings:

/user/config/system:
	languages:
	  supported: (Note: no Spanish)
	    - it
	    - fr
	    - en
	  translations: true
	  translations_fallback: false
/user/config/site:
	default_lang: en
user/pages/
	01.home (Note: page for supported languages + Spanish)
		default.en.md
		default.fr.md
		default.it.md
		default.es.md

The site has a theme with the following translations:

languages.yaml: (Note: No Italian, No Spanish)
	fr:
	  TRANSLATE_ME: Traduis-moi
	en:
	  TRANSLATE_ME: Translate me

The themes partials/base.html.twig looks like:

<p>html_lang: {{ html_lang }}<br/>
Is language supported: {{ html_lang in config.system.languages.supported ? 'Yes' : 'No' }}<br/>
html_lang == getLanguage: {{ html_lang == grav.language.getLanguage ? 'Yes' : 'No' }}<br/>
Is translated: {{ 'TRANSLATE_ME'|t == 'TRANSLATE_ME' ? 'No' : 'Yes' }}<br/>
Translation: {{ 'TRANSLATE_ME'|t }}</p>

This setup yielded the following when browsing to the different pages:

http://localhost/grav-dev/en
	html_lang: en
	Is language supported: Yes
	html_lang == getLanguage: Yes
	Is translated: Yes
	Translation: Translate me

http://localhost/grav-dev/fr
	html_lang: fr
	Is language supported: Yes
	html_lang == getLanguage: Yes
	Is translated: Yes
	Translation: Traduis-moi


http://localhost/grav-dev/it
	html_lang: en
	Is language supported: Yes
	html_lang == getLanguage: No
	Is translated: No
	Translation: TRANSLATE_ME

http://localhost/grav-dev/es -> Page does not exist error
	html_lang: en
	Is language supported: Yes
	html_lang == getLanguage: No
	Is translated: No
	Translation: TRANSLATE_ME
2 Likes