0

I have a paragraph with an image field. If the image field is empty, I want to display a default value. I do not want to just set the default image because an editor could remove that. Here is my code so far:

{% if content.field_image|render = true %}
    {{ content.field_image }}
{% else %}
    {% include "/themes/mytheme/img/my_img.png” %}
{% endif %}

How can I get the image at that filepath to show up in the template?

  • 1
    You might be overthinking it - remember it's an HTML template, you can just use an <img> tag – Clive Sep 26 '18 at 20:38
  • @clive is the image path relative or does it need a root path? I attempted a relative path but it didn’t work. The relative path is something like “../../../img/my_img.png” – lane Sep 26 '18 at 22:13
  • @Clive this was the answer. Wanna make your comment into an answer so I can give it to you? – lane Sep 27 '18 at 19:37
1

For example if your default image called default_img.png inside images folder inside your theme MyTheme.

You can try the following:

  1. implement hook_preprocess_HOOK

/**
 2. Implements hook_preprocess_HOOK().
 */
function extended_url_preprocess_paragraph(&$variables) {
  $variables['theme_path'] = drupal_get_path('theme', 'MyTheme');
}

  1. In your twig you can do something like:
{% if content.field_image|render = true %}  
    {{ content.field_image }}  
{% else %}  
<img src="{{ theme_path ~ directory }}/images/default_img.png"/>
{% endif %}
| improve this answer | |

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.