您可以创建一个函数来为您下载此文件,并使其可用于 twig。
想法:
- 您创建了一个目录
app/Resources/views/temp,因此可以通过:temp:file.html.twig 访问树枝文件
- 在您的 twig 文件中,您将使用
remote_file() 函数来包装第一个 include 的参数
- 您的文件将由您的函数下载到
temp 目录中,名称为随机
- 您的函数将返回一个树枝路径以在本地访问文件(
:temp:file.html.twig)
- 不要忘记自动清除太旧的临时文件! (一个cron?)
目录
创建一个临时目录,让你的 symfony 目录树看起来像这样:
扩展
在你的包中,创建一个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 配置文件中,添加以下内容:
下面parameters:
fuz_tools.twig.remote_file_extension.class: Fuz\TestBundle\Twig\Extension\RemoteFileExtension
下面services:
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'} %}
当我运行我的代码时,我得到:
还有一些注意事项
您应该考虑到 twig 文件是您的应用程序的一部分。 twig 文件不是资产,因为它需要由 Symfony2 解释,具有一些逻辑,一些优化等等。你所做的实际上相当于在执行 PHP 文件之前对其进行远程包含,我认为这是一种奇怪的架构。
无论如何,您的问题很有趣,祝您实施顺利。