Display different icons depending on field value I am trying to produce a result that requires PHP code to evaluate whether a Drupal 8 node field is a "x", an "f", a "m", a "h", or an "l".

Thanks to some help on an earlier question, I've accomplished my task (to replace the value with a useful icon) when the value is binary: if it exists, show this. If it's empty, show nothing. I've done this via CSS.

Now I'd like to extract the actual value of the node field, and display different icons based on its value.

I am not planning to do this via a function, but rather by code on the node itself.  Is there some syntax I can use within the php that will extract this?  So that I can have the equivalent of:

$price = $node[field][value];


then I'd do:

if ($price == "m") { // use icon X }
else if ($price == "h") { // use icon Y };


Thank you for any and all help/suggestions!
This only requires one field. It sounds like it is a list (text) field to me.

This should be done as a new variable to the node template by way of using hook_preprocess_node in your MYTHEME.theme (replace any instance of MYTHEME with your actual themes name, i.e. bartik) file. Here is an example:

function mytheme_preprocess_node(&amp;$variables) {
  $type = $variables['node']-&gt;getType();

  if ($type == 'NODE_TYPE') {
    $price = $variables['node']-&gt;get('field_name')-&gt;value;

    switch ($price) {
      case "m":
        $variables['custom_icon'] = 'icon1';
        break;

      case "h":
        $variables['custom_icon'] = 'icon2';
        break;

      case "x":
        $variables['custom_icon'] = 'icon3';
        break;

      case "f":
        $variables['custom_icon'] = 'icon4';
        break;

      case "l":
        $variables['custom_icon'] = 'icon5';
        break;

      default:
        $variables['custom_icon'] = FALSE;
        break;
    }
  }
}


Then, create a node--NODE-TYPE.html.twig file, where NODE-TYPE is the machine name (bundle) of the node in question (ex. article, page, product). 

In this file, you now have a new variable available to use, which would be output with:

{% if custom_icon %}
  {{ custom_icon }}
{% endif %}


If no value, or value does not match whats expected, the switch statement will set the variable to FALSE so you can check in Twig if you should output it or not.