Ad

How Can I Render Title Attribute In Img Tag Conditionally?

- 1 answer

I'm trying to render a title Attribute in an HTML image tag conditionally with twig (in October CMS).

I tried following with attributes.setAttribute, but failed:

<img class="my-class" src="{{ myImage.path }}" {{ myImage.title ? attributes.setAttribute('title', myImage.title) : {} }}>

Is there any better way to do that? Or do I really have to do this one:

{% if myImage.title %}
   <img class="my-class" src="{{ myImage.path }}" title="{{ myImage.title }}">
{% else %}
   <img class="my-class" src="{{ myImage.path }}">
{% endif %}

I'm using twig in octoberCMS...

Ad

Answer

You can use the below code

{% set titleAttribute =  myImage.title ? 'title="' ~ myImage.title ~ '"' : '' %}
<img class="my-class" src="{{ myImage.path }}" {{titleAttribute|raw}} />

OR inline version

<img 
    class="my-class" 
    src="{{ myImage.path }}" 
    {{(myImage.title ? 'title="' ~ myImage.title ~ '"' : '')|raw}} 
/>

if any doubt please comment.

Ad
source: stackoverflow.com
Ad