azz*_*y81 3 php twig symfony-2.3
在Symfony 2.3中使用Twig我需要能够在树枝模板中选择远程资产.
所以我有一个像这样的体块的树枝模板:
{% block body %}
{% include 'http://asset.remotelocation.co.uk/template.html.twig' %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
正如你可以看到它试图包含一个远程树枝模板.这可能因为symfony只是错误说它无法找到模板吗?
我的代码中的树枝模板位置是正确的,因为我可以浏览到浏览器中的模板网址.
任何帮助都很适合.=)
PS远程位置只是我们拥有共享资产的其他网络服务器之一.
You can create a function that will download this file for you, and make it available for twig.
The idea :
app/Resources/views/temp, so a twig files can be accessed at :temp:file.html.twigremote_file()函数来包装第一个include参数temp目录中以随机名称下载:temp:file.html.twig)创建一个临时目录,以便您的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';
}
}
Run Code Online (Sandbox Code Playgroud)
在services.yml配置文件中,添加以下内容:
下面parameters:
fuz_tools.twig.remote_file_extension.class: Fuz\TestBundle\Twig\Extension\RemoteFileExtension
Run Code Online (Sandbox Code Playgroud)
下面services:
fuz_tools.twig.remote_file_extension:
class: '%fuz_tools.twig.remote_file_extension.class%'
arguments: ['@kernel']
tags:
- { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)
我创建了一个现有的http://localhost:8888/test.html.twig.它只包含:
Hello, {{ name }}!
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我输入以下行:
{% include remote_file('http://localhost:8888/test.html.twig') with {'name': 'Alain'} %}
Run Code Online (Sandbox Code Playgroud)
当我运行我的代码时,我得到:

您应该考虑将twig文件作为应用程序的一部分.twig文件不是资产,因为它需要由Symfony2,一些逻辑,一些优化等来解释.你所做的实际上与执行它之前的PHP文件的远程包含相当,我认为是奇怪的架构.
无论如何,你的问题很有趣,祝你好好实施.
| 归档时间: |
|
| 查看次数: |
3625 次 |
| 最近记录: |