【问题标题】:How use a custom function Twig-symfony如何使用自定义函数 Twig-symfony
【发布时间】:2020-11-09 02:46:08
【问题描述】:

我们有一个 Symfony 3.4 项目,带有 Twig 模板和 FOSUserBundle 的身份验证系统。

它是多域的,主要管理客户和供应商数据,效果很好,但是现在我在用户注册时遇到了一个不知道如何解决的问题。

我需要根据域,它可以在注册时显示一个或另一个树枝模板。

搜索文档并了解如何编写自定义树枝扩展 https://symfony.com/doc/3.4/templating/twig_extension.html

这是我的功能,与示例中的功能几乎相同

<?php

// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('server', [$this, 'serverName']),
        ];
    }

    public function calculateArea(int $width, int $length)
    {
        return $width * $length;
    }

    public function serverName()
    {
        $serverName = "$_SERVER[SERVER_NAME]";
        return $serverName;
    }
}

问题是,我如何在 Twig 中使用我的函数?我需要根据它连接的域,它向我们展示了一个注册表单或类似的东西:

{% extends "@FOSUser/layout.html.twig" %}

{% block fos_user_content %}

    {% if serverName == "xxxxx"%}
        {% include "@FOSUser/Registration/register_content_cliente.html.twig" %}
    {% else %}
        {% include "@FOSUser/Registration/register_content_proveedor.html.twig" %}
    {% endif %}
    
{% endblock fos_user_content %}

不是这样的:

{{ serverName }}
{{ server }}

{% serverName %}
{% server %}

【问题讨论】:

    标签: symfony twig fosuserbundle


    【解决方案1】:

    就像使用 php 一样,你必须使用 () 调用函数,所以 serverName() server(),因为这就是你在 AppExtension::getFunctions() 中调用的函数(第一个参数)。

    您可能希望将该函数替换为所谓的test。然后您可以执行以下操作:

    {% if 'example.com' is serverName %}
    {% endif %}
    

    代码可能类似于:

    class AppExtension extends AbstractExtension
    {
        public function getTests()
        {
            return [
                new TwigTest('serverName', [$this, 'isServerName']),
            ];
        }
    
        public function isServerName(string $serverName)
        {
            return $serverName === $_SERVER[SERVER_NAME];
        }
    }
    

    另外,在您的模板中,您始终可以使用变量app.request 访问请求,您可以使用 Symfony 的 Request 对象上的一种方法来请求当前服务器名称。例如,您可以使用Request::getHost() 进行比较:

    {% if app.request.host == 'example.com' %}
    {% endif %}
    

    不需要任何功能或测试或其他树枝扩展。

    【讨论】:

    猜你喜欢
    • 2014-11-11
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多