我有container.twig包括component.twig并传递一个名为'mock'的对象.
在container.twig中:
{% set mock = {
title : "This is my title"
}
%}
{% include 'component.twig' with mock %}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我想将模拟数据移动到自己的文件.这不起作用:
Container.twig
{% include 'component.twig' with 'mock.twig' %}
Run Code Online (Sandbox Code Playgroud)
在mock.twig中
{% set mock = {
title : "This is my title"
}
%}
Run Code Online (Sandbox Code Playgroud)
我使用gulp-twig但它在大多数方面像标准树枝一样工作.https://github.com/zimmen/gulp-twig
Twig 上下文永远不会存储在模板对象中,因此很难找到一种干净的方法来实现这一点。例如,以下 Twig 代码:
{% set test = 'Hello, world' %}
Run Code Online (Sandbox Code Playgroud)
将编译为:
<?php
class __TwigTemplate_20df0122e7c88760565e671dea7b7d68c33516f833acc39288f926e234b08380 extends Twig_Template
{
/* ... */
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["test"] = "Hello, world";
}
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,继承的上下文不会通过引用传递给 doDisplay 方法,并且永远不会存储在对象本身中(如$this->context = $context)。这种设计允许模板可重复使用,并且内存友好。
不知道大家是否了解Twig中的全局变量。你可以用它们做很多黑客活动。
最简单的用法是将所有全局变量加载到 twig 环境中。
$loader = new Twig_Loader_Filesystem(__DIR__.'/view');
$env = new Twig_Environment($loader);
$env->addGlobal('foo', 'bar');
$env->addGlobal('Hello', 'world!');
Run Code Online (Sandbox Code Playgroud)
然后,您可以在整个应用程序中使用{{ foo }}and 。{{ Hello }}
但这里有两个问题:
当您尝试从树枝文件加载变量时,我假设您有很多变量需要根据您的功能进行初始化,并且不想一直加载所有内容。
您正在从 PHP 脚本而不是从 Twig 加载变量,并且您的问题想要从 twig 文件导入变量。
您还可以创建一个存储扩展,它提供save将某些模板的上下文保留在某处的功能,以及restore将此存储的上下文合并到另一个模板中的功能。
proof_of_concept.php
<?php
require __DIR__.'/vendor/autoload.php';
class StorageTwigExtension extends Twig_Extension
{
protected $storage = [];
public function getFunctions() {
return [
new Twig_SimpleFunction('save', [$this, 'save'], ['needs_context' => true]),
new Twig_SimpleFunction('restore', [$this, 'restore'], ['needs_context' => true]),
];
}
public function save($context, $name) {
$this->storage = array_merge($this->storage, $context);
}
public function restore(&$context, $name) {
$context = array_merge($context, $this->storage);
}
public function getName() {
return 'storage';
}
}
/* usage example */
$loader = new Twig_Loader_Filesystem(__DIR__.'/view');
$env = new Twig_Environment($loader);
$env->addExtension(new StorageTwigExtension());
echo $env->render('test.twig'), PHP_EOL;
Run Code Online (Sandbox Code Playgroud)
twig/variables.twig
{% set foo = 'bar' %}
{% set Hello = 'world!' %}
{{ save('test') }}
Run Code Online (Sandbox Code Playgroud)
twig/test.twig
{% include 'variables.twig' %}
{{ restore('test') }}
{{ foo }}
Run Code Online (Sandbox Code Playgroud)
注意:如果您只想导入变量而不实际渲染里面的内容twig/variables.twig,您还可以使用:
{% set tmp = include('variables.twig') %}
{{ restore('test') }}
{{ foo }}
Run Code Online (Sandbox Code Playgroud)
我不习惯 JavaScript twig 端口,但看起来你仍然可以扩展它,那就是你的了:)