php - 使用 TWIG 加载远程文件

标签 php twig symfony-2.3

在 Symfony 2.3 中使用 Twig 我需要能够在 Twig 模板中选择远程资源。

所以我有一个带有主体 block 的 Twig 模板,如下所示:

{% block body %}
    {% include 'http://asset.remotelocation.co.uk/template.html.twig' %}
{% endblock %}

正如您所看到的,它试图包含一个远程 Twig 模板。这是可能的,因为 symfony 只是错误地说它找不到模板吗?

我的代码中的 twig 模板位置是正确的,因为我可以在浏览器中浏览到模板 url。

非常感谢任何帮助。 =)

P.S 远程位置只是我们持有共享 Assets 的其他网络服务器之一。

最佳答案

您可以创建一个函数来为您下载此文件,并使其可用于 twig。

想法:

  • 您创建一个目录 app/Resources/views/temp,因此可以在 :temp:file.html.twig 访问 twig 文件
  • 在您的 twig 文件中,您将使用 remote_file() 函数来包装第一个 include 的参数
  • 您的文件将由您的函数下载到 temp 目录中,名称为随机
  • 您的函数将返回一个 Twig 路径以访问本地文件(:temp:file.html.twig)
  • 不要忘记自动执行某些操作以清除太旧的临时文件! (一个 cron?)

目录

创建一个临时目录,使您的 symfony 目录树如下所示:

enter image description here

扩展

在您的包中,创建一个 Twig\Extension 目录。在那里,使用以下代码创建一个 RemoteFileExtension.php 文件。注意:不要忘记用你的替换我的命名空间。

<?php

namespace Fuz\TestBundle\Twig\Extension;

use Symfony\Component\HttpKernel\KernelInterface;

class RemoteFileExtension extends \Twig_Extension
{

    private $kernel;

    public function __construct(KernelInterface $kernel)
    {
        $this->kernel = $kernel;
    }

    public function getFunctions()
    {
        return array(
                'remote_file' => new \Twig_Function_Method($this, 'remote_file'),
        );
    }

    public function remote_file($url)
    {
        $contents = file_get_contents($url);
        $file = $this->kernel->getRootDir() . "/Resources/views/temp/" . sha1($contents) . '.html.twig';
        if (!is_file($file))
        {
            file_put_contents($file, $contents);
        }
        return ':temp:' . basename($file);
    }

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

}

在您的 services.yml 配置文件中,添加以下内容:

低于参数:

fuz_tools.twig.remote_file_extension.class: Fuz\TestBundle\Twig\Extension\RemoteFileExtension

服务下方:

fuz_tools.twig.remote_file_extension:
    class: '%fuz_tools.twig.remote_file_extension.class%'
    arguments: ['@kernel']
    tags:
      - { name: twig.extension }

测试一下!

我创建了一个现有的 http://localhost:8888/test.html.twig。它只包含:

Hello, {{ name }}! 

在我的应用程序中,我放置了以下行:

{% include remote_file('http://localhost:8888/test.html.twig') with {'name': 'Alain'} %}

当我运行我的代码时,我得到:

enter image description here

一些注意事项

您应该考虑将 twig 文件作为您应用程序的一部分。 twig 文件不是 Assets ,因为它需要由 Symfony2 解释,有一些逻辑,有一些优化等等。您实际上所做的相当于在执行 PHP 文件之前远程包含它,我认为这是一种奇怪的架构。

无论如何,您的问题很有趣,祝您实现顺利。

关于php - 使用 TWIG 加载远程文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19030721/

相关文章:

javascript - 来自数据库数据的内容可更改 Dropdownlist

php - 通过代理使用 https 请求的 file_get_contents

wordpress - Twig 分页无法正常工作

session-cookies - 如果启用 cookie,Symfony ESI 会破坏 Varnish 缓存

php - 获取没有 TLD 的域名

php - Laravel 有很多分离

php - 与 TWIG 的关系

include - 交响乐 4 : Multiple inclusion of a file

php - Symfony2 : How to change hidden field value on PRE_SUBMIT

security - Symfony 2.3 Bad Credentials 自定义提供程序