0

I am templating a resource page that has 5 different types of resources. I want to display a specific icon based on the type of resource. I want to do this programmatically so that later, users can upload a document, choose what type of resource it is, and the icon will automatically be displayed.

Now I'd like to be able to complete the logic of this inside the node--resource-asset.html.twig template using a for or if statement.

enter image description here This is the kint display for the field_resource_type array. I want to generate the icon based on the markup string. This is what I've tried

{% for markup in content.field_resource_type %}
{% if markup == 'Datasheet' %}
<img class="icon" src="/img/icon_datasheet.png">
{% elseif markup == 'Whitesheet' %}
<img class="icon" src="/img/icon_whitepaper.png">
{% else %}
<img class="icon" src="/img/icon_casestudy.png">
{% endif %}
{% endfor %}

Nothing renders. Any suggestions on what I should be using as the key to call the correct part of the field?

2
  • This way the var markup will never get value 'Datasheet', Try {% for markup in content.field_resource_type[0] %}. This for statement is really necessary? Why you just try get content.field_resource_type[0]['#markup'] ?
    – Vagner
    Commented Mar 4, 2016 at 0:05
  • You were right, I was just overthinking the problem. content.field_resource_type[0]['#markup'] worked like a charm. Thank you! Commented Mar 4, 2016 at 16:37

1 Answer 1

1

You have two primary things avaiable in a node template.

content: That contains rendered markup. Use it to print stuff.

node: This contains the node object with the raw values. Use this for comparisons and accessing the unformatted values. The same raw values would also be accessible through #items in content, but it's much more complicated to access.

So in your case, access the value with node.field_resource_type.value.

Note that this contains the key of the list field, and not the displayed label. I would recommend to always specify explicit keys (e.g., put datasheet|Datasheet in the allowed values field). Then you can also reliably translate those labels if you have a multilingual site and your template doesn't break.

Unless you actually have multiple values in there, you also don't need a loop. But if you do, you can loop over it with for item in node.field_resource_type and then use item.value.

See also http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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