首页 > 解决方案 > 使用记录值作为 Twig 函数参数

问题描述

我正在编写一个 Bolt 扩展来解析 XML 文件并返回 XML 的反序列化对象树。解析和反序列化工作就像一个魅力,但我无法从页面记录中获取文件名作为 Twig 函数的参数。

扩展代码(简化)是:

class CompetitionExtension extends SimpleExtension
{
    protected function registerTwigFunctions()
    {
        return [
            'competition' => 'competitionFunction',
        ];
    }

    /**
     * Load and parse the competition XML.
     *
     * @param string $filename
     * @return Competition
     */
    public function competitionFunction(string $filename) : Competition
    {
        $competition = null;
        $loader = new FileLoader($filename);
        if ($loader->openFile()) {
            $competition = $loader->parse();
        }
        return $competition;
    }
}

contenttype扩展的homepage)添加是:

competitionxml:
    type: file
    upload: competitions
    group: content

文件的上传也没有问题,但是下面的 Twig 模板代码给出了错误:

{% set xmlfile = homepage.competitionxml %}
{% set comp = competition(xmlfile) %}

使用dump我看到它xmlfile具有正确的值。但我收到以下错误:

An exception has been thrown during the rendering of a template ("Notice: Undefined variable: filename") in "index.twig" at line 27.

那么如何使用附件的文件名作为 Twig 函数的参数呢?

标签: phptwigbolt-cms

解决方案


推荐阅读