如何将上传的 SVG 输出为 Timber 中的代码

问题描述

我正在使用 wordpress + Timber 构建一个网站,需要输出一个上传 SVG 图像作为代码

这是我所拥有的,但它不起作用:

{% for block in section.blocks %}
    <img src="{{ Image(block.icon).src }}"> <!-- this works as exptected -->
   {{ function('file_get_contents',Image(block.icon).src) }} <!-- this fails -->
{% endfor %}

生成错误是“无法打开流”,但 Image(block.icon).src 提供的 URL 是完整、有效的 URL(即我可以在浏览器中访问它并加载)。

我错过了什么?或者有更好的方法吗?

解决方法

有两种方法可以在 twig 文件中加载外部代码。

包含方法:

{% include 'my.svg.twig' %} 

Twig 源函数:

{{ source(my.svg.svg) }}

此外,您可以使用 WP_PLUGIN_DIR + 您的文件 url 尝试使用 file_get_contents 常量。

{{ function('file_get_contents','WP_PLUGIN_DIR'.Image(block.icon).src) }}

附注。源函数的工作方式类似于 include。

关于树枝源函数的更多信息在这里:https://twig.symfony.com/doc/2.x/functions/source.html