For a teaser view mode I want to display the language of the content. I can get the langcode in twig with: {{ node.langcode.value }} But how can I display the language name? In the field display I get only the string with "Language English", but I want only the name without any other thinks like "Language ...".

One way is to use preprocess node:

function mytheme_preprocess_node(&$variables) {
  $variables['lang_name'] = $variables['node']->language()->getName()

in the template file:

{{ lang_name }}

Is there a pure twig solution possible?


If you want to use the method language() in Twig

{{ node.language.name }}

you have to add it to the whitelist of the Twig sandbox policy in settings.php:

$settings['twig_sandbox_whitelisted_methods'] = [
|improve this answer|||||
  • Thanks for this, it works perfect! So I can rewrite in the settings.php the 'twig_sandbox_whitelisted_methods' from the core/lib/Drupal/Core/Template/TwigSandboxPolicy.php and add other things like 'url' and so on? – Bruno Apr 7 '18 at 12:13
  • Yes, you can do this, but don't add methods like delete(). – 4k4 Apr 7 '18 at 15:28

Use {{ node.language().getName() }} or {{ node.language().name }} (might not work).

With any object, like a node, you can call methods / get properties in twig by just using a '.' as the PhP ->. Generally, getXXX() can be shortened to XXX. Occationally, you may need to add a .value or .toString() on the end to convert from the format returned to string.

Here's the formal twig reference for this. The implementation notes give some guidance on how short names work.

|improve this answer|||||
  • oh sorry, i forgot to write this down! I tested it before For {{ node.language().getName() }} i get a blank page with kint() or an error page if i try to print it also for {{ node.language() }}. {{ node.langcode.getName() }} gives me the string "langcode" – Bruno Apr 6 '18 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.