【问题标题】:Symfony asset url when running from console从控制台运行时的 Symfony 资产 url
【发布时间】:2016-09-16 01:52:25
【问题描述】:

从命令行(控制台命令)运行时,我想在树枝模板中添加资产(图像)完整 url(带有域和基)。它旨在发送到电子邮件。

问题是,在控制台上运行时使用 absolute_url(asset()) 不包括主机和基本路径。

此外,正如 http://symfony.com/doc/current/console/request_context.html 中所述,它仅适用于 url,不适用于资产。

我还尝试在从控制台运行时设置路由器上下文:

$context = $this->getContainer()->get('router')->getContext();
$context->setHost($defaultDomain);
$context->setScheme($scheme);

没有成功。有什么想法吗?

【问题讨论】:

    标签: php symfony twig


    【解决方案1】:

    要配置 URL 生成器使用的请求上下文 - 您可以重新定义它用作默认值的参数以更改默认主机 (localhost) 和方案 (http)

    # app/config/parameters.yml
    parameters:
       router.request_context.host: example.org
       router.request_context.scheme: https
       router.request_context.base_url: my/path
    

    http://symfony.com/doc/current/console/request_context.html

    #command
    /** @var \Twig_Environment $twig */
    $twig = $this->getContainer()->get('twig');
    die($twig->render('view.html.twig'));
    
    #view.html.twig
    {{ absolute_url(asset('images/logo.png')) }}
    
    #output
    https://example.org/images/logo.png
    

    【讨论】:

      【解决方案2】:

      在我的应用程序中,特别针对这种电子邮件情况,我在 Twig 配置中添加了全局变量:

      # app/config/config.yml
      twig:
          globals:
              site_addr: "%site_addr%"
      

      并在parameters.yml中设置这个变量

      # app/config/parameters.yml
      site_addr: https://some.site
      

      最后,在每个电子邮件模板中我都使用了这个:

      # AppBundle/Resources/views/Emails/layout.html.twig
      <img src="{{ site_addr ~ asset('SomeAssetName') }}"/>
      

      【讨论】:

        【解决方案3】:

        你必须定义base_urls参数。

        framework:
            assets:
                base_urls: ['http://localhost:8000']
        

        【讨论】:

          【解决方案4】:

          您可以使用此解决方案,它不需要在配置中添加任何变量或参数,并且与 Twig 用于{{ absolute_url() }} 的功能相同

          public function yourAction(AssetsHelper $assetsHelper, HttpFoundationExtension $httpExtension)
          {
              $assetsPath = $assetsHelper->getUrl('/img/test.jpg');
              $assetFullUrl = $httpExtension->generateAbsoluteUrl($assetPath);
          }
          

          您的资产的完整网址将在$assetFullUrl

          【讨论】:

            猜你喜欢
            • 2013-03-02
            • 1970-01-01
            • 2020-06-05
            • 1970-01-01
            • 1970-01-01
            • 2016-10-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多