【问题标题】:Symfony, Twig: Persistent route parametersSymfony,Twig:持久路由参数
【发布时间】:2016-06-24 00:03:23
【问题描述】:

我正在 Symfony3 中制作应用程序。部分应用程序由动态子域划分 --- 子域由 slug 表示。

subdomains:
     host: "{slug}.{domain}"
     default:
           slug: example
     ...

当在此类路由的本地示例上运行时,例如http://a.localhost

当我在 Twig 中创建链接时,无论是使用 {{ url('route') }} 还是 {{ path('route') }},子域总是忘记,并且参数中的 slug 属于默认值example,总是在做路线http://example.localhost

有没有办法隐式复制参数,或者标记一些参数持久化,这样我就不用像{{ url('route', {'slug' : slug}) }}这样让所有的链接都包含slug,才能留下在子域上?

谢谢

【问题讨论】:

  • 分析器对“路由”面板上的“路由参数”有何看法? (/app_dev.php/_profiler/latest?panel=router)
  • @TobiasXy slug 参数在带有 _localedomain 参数的“路由参数”中按预期列出。没有提供其他信息。

标签: parameters routes twig slug symfony


【解决方案1】:

我创建了一个TwigExtension 用于在子域中生成链接。

如果可以像我在问题中提到的那样使某些参数“持久”,我会更喜欢。这些将隐含地跨越相对路径,但可能通过显式参数选择无效。如果这不可能,我认为这个选项比手动添加参数更好,也是目前为止的最佳选项。

扩展类

/**
 * ApplicationExtension constructor.
 *
 * @param Router $router
 * @param RequestStack $requestStack
 */
public function __construct(Router $router, RequestStack $requestStack)
{
    $this->router = $router;
    $this->requestStack = $requestStack;
}

public function getFunctions()
{
    return [
            new \Twig_SimpleFunction('domainPath', [
                    $this,
                    'domainPath'
            ]),
    ];
}

public function domainPath($route_name, $params = [])
{
    if (!array_key_exists('slug', $params)) {
        $params['slug'] = $this->requestStack->getCurrentRequest()->attributes->get('slug');
    }
    return $this->router->generate($route_name, $params);
}

public function getName()
{
    return 'application_extension';
}

注册服务(DI和标签)

application.twig.application_extension:
        class: ApplicationBundle\Twig\ApplicationExtension
        arguments: ["@router", "@request_stack"]
        public: false
        tags:
            - { name: twig.extension }

在模板中使用

{{ domainPath('route_name') }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2018-12-28
    • 2011-03-05
    • 1970-01-01
    • 2016-04-27
    相关资源
    最近更新 更多