【问题标题】:How can I render title attribute in img tag conditionally?如何有条件地在 img 标签中呈现 title 属性?
【发布时间】:2021-02-28 21:07:00
【问题描述】:

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

我尝试使用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...

【问题讨论】:

  • attributes.setAttribute 属性未定义。试试 this.setAttribute
  • 你真的需要没有 title 属性吗?如果 myImage.title 是一个空字符串,您可以完全放弃在 html 中使用条件。它将呈现一个空的标题,在功能上与根本没有标题相同。

标签: html twig octobercms


【解决方案1】:

你可以使用下面的代码

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

或内联版本

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

如有任何疑问,请发表评论。

【讨论】:

  • 你不需要twig中额外的: ''
  • 我在那里添加是因为如果用户想要添加默认标题或其他内容,他们可以有一个选项,否则如果他们想要添加并且看不到任何方法,他们会感到困惑。所以最好把它加在那里。因为每个人都不太了解 twig
  • 没错,只是一个注释
猜你喜欢
  • 1970-01-01
  • 2011-10-19
  • 2014-03-12
  • 2013-04-29
  • 1970-01-01
  • 2019-10-28
  • 2023-04-07
  • 2015-05-26
  • 2021-09-28
相关资源
最近更新 更多