如何有条件地在 img 标签中渲染 title 属性?

How can I render title attribute in img tag conditionally?

我正在尝试使用 twig(在十月 CMS 中)有条件地在 HTML 图像标签中呈现标题属性。

我尝试跟随 attributes.setAttribute,但失败了:

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

有更好的方法吗?还是我真的必须这样做:

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

我在 octoberCMS 中使用 twig...

您可以使用下面的代码

{% 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}} 
/>

如有疑问请评论。