Twig模板动态拼接图片路径时移除字符串空格的方法求助
解决方案
问题根因
- 你遇到的标签解析异常是因为
attribute.text本身携带空格,渲染img标签时如果src属性值没有被双引号完整包裹,空格会被浏览器识别为HTML属性分隔符,才会出现Cushion" modified.png=""的错误结构 - 你的需求需要先移除
attribute.text中的所有空格后再拼接路径,才能得到符合要求的文件名
实现代码
首先使用Twig的replace过滤器移除文本内所有空格,再拼接路径:
{% if attribute.name == "Shape" %} {# 移除文本中所有空格 #} {% set processed_text = attribute.text|replace({' ': ''}) %} {% set image = 'image/catalog/Products/shapes/sample/' ~ processed_text ~ '.png' %} {% endif %}
如果需要和你给出的目标路径Cushionmodified.png完全匹配(即首字母保留大写,后续所有字符转小写),可以调整为:
{% if attribute.name == "Shape" %} {% set no_space_text = attribute.text|replace({' ': ''}) %} {# 首字母保留大写,剩余字符统一转小写 #} {% set processed_text = no_space_text|first ~ no_space_text|slice(1)|lower %} {% set image = 'image/catalog/Products/shapes/sample/' ~ processed_text ~ '.png' %} {% endif %}
渲染注意事项
输出img标签时,必须给src属性值加上双引号,避免浏览器解析异常:
<img src="{{ image }}" alt="产品形状图">
内容的提问来源于stack exchange,提问作者Rouf Wani
相关产品推荐
相关产品推荐

