eexit / twig-context-parser
此包已被废弃且不再维护。未建议替代包。
以实用方式获取Twig模板上下文变量。
0.1.0
2013-09-28 16:20 UTC
Requires
- php: >=5.3.3
- twig/twig: >=1.8,<2.0-dev
This package is not auto-updated.
Last update: 2021-08-15 23:54:02 UTC
README
这个小脚本使用内部Twig标记/解析器/编译器从渲染上下文中获取模板变量。
如果你正在构建基于平面文件Twig的CMS,使用解析的平面文件变量进行操作可能非常有用。有许多用途。
该解析器基本上返回你在Twig中设置的变量,无论它多么复杂,都使用set块
{% set foo = [
{"bar":"baz"},
"bar",
range(0, 12, 2),
["yux", {
"baz":"yea",
"bar":"foo",
"range":range(0, 100)
}]
] %}
将输出
array(1) {
'foo' =>
array(4) {
[0] =>
array(1) {
'bar' =>
string(3) "baz"
}
[1] =>
string(3) "bar"
[2] =>
array(7) {
[0] =>
int(0)
[1] =>
int(2)
...
[6] =>
int(12)
}
[3] =>
array(2) {
[0] =>
string(3) "yux"
[1] =>
array(3) {
'baz' =>
string(3) "yea"
'bar' =>
string(3) "foo"
'range' =>
array(101) {
[0] =>
int(0)
[1] =>
int(1)
...
[99] =>
int(99)
[100] =>
int(100)
}
}
}
}
}
安装
假设你正在使用composer,将其添加到你的composer.json
{
"require": {
"eexit/twig-context-parser": "0.1.*"
}
}
用法
use Eexit\Twig\ContextParser\ContextParser; $loader = new \Twig_Loader_String(); $twig = new \Twig_Environment($loader); $template = $twig->parse($twig->tokenize('{% set foo = "bar" %}{% set baz = "yux" %}')); $context = new ContextParser($twig); var_dump($context->parse($template)->getContext()); /* array(2) { 'foo' => string(3) "bar" 'baz' => string(3) "yux" } */
ContextParser::getParser()将一次性返回节点上下文。一旦调用该方法,再次调用将返回空值。这允许使用相同的ContextParser实例连续解析多个模板。