unclecheese / reflection-templates
提供对 SilverStripe 模板的反射,具有获取变量和块的 API,类似于 PHP 的 ReflectionClass。
dev-master
2016-10-18 01:33 UTC
Requires
- silverstripe/framework: ~3.1
This package is auto-updated.
Last update: 2024-08-29 04:09:02 UTC
README
一组用于反射 SilverStripe 模板、获取变量和块的元数据的类,类似于 PHP 的 ReflectionClass。
安装
composer require unclecheese/reflection-templates:dev-master
要求
SilverStripe 3.1 或更高版本
用法
给定如下模板
<div> <h2>$Headline</h2> <div>$Image.CroppedImage(200,200)</div> <h3>$Category.Title</h3> <% if $Featured %>it's featured<% end_if %> <ul> <% loop $Items %> <li>$Title ($Date.Nice)</li> <% if $Articles %> <ul> <% loop $Articles %> <li>This article, called $ArticleTitle is related to $Up.Title <% if $Published %>published<% end _if %></li> <% end_loop %> </ul> <% end_if %> <% end_loop %> <% with $FeaturedProduct %> <h3>$Description</h3> <% end_with %> </div>
我们可以使用 ReflectionTemplate
来反射它,如下所示
$reflector = ReflectionTemplate::create(); $reflector->process(file_get_contents('/path/to/template.ss')); foreach($reflector->getTopLevelVars() as $varName => $type) { echo "The template variable $varName is likely a $type\n"; } foreach($reflector->getTopLevelBlocks() as $block) { echo "There is a block at the top level named {$block->getName()}\n"; echo $block->isLoop() ? "\tThis block is a loop\n" : "\tThis block is a with\n"; foreach($block->getVars() as $var => $type) { echo "\tThe top level block {$block->getName()} contains a variable named $var that is likely a $type\n"; } foreach($block->getChildren() as $child) { echo "\tThere is a child block named {$child->getName()}. It has the following vars:\n"; foreach($child->getVars() as $v => $t) { echo "\t\tThe nested block {$child->getName()} contains a variable named $v that is likely a $t\n"; } } }
这将产生以下结果
The template variable Headline is likely a Text
The template variable Image is likely a Image
The template variable Category is likely a has_one
The template variable Featured is likely a Boolean
There is a block at the top level named Items
This block is a loop
The top level block Items contains a variable named Title that is likely a Text
The top level block Items contains a variable named Date that is likely a Date
There is a child block named Articles. It has the following vars:
The nested block Articles contains a variable named ArticleTitle that is likely a Text
The nested block Articles contains a variable named Published that is likely a Boolean
There is a block at the top level named FeaturedProduct
This block is a with
The top level block FeaturedProduct contains a variable named Description that is likely a Text
上下文模板反射
您可以使用两个上下文相关的反射器之一,仅显示用户定义的变量和块。
SiteTreeReflectionTemplate
预加载了关于所有SiteTree
和ContentController
上下文中可用的方法和变量的信息,并过滤掉了诸如$Menu
、$SiteConfig
等内容。EmailReflectionTemplate
工作方式类似,过滤掉了所有电子邮件中可用的诸如To
、Subject
等变量。
在这个世界上所有美好的事物,为什么?!
最近我发现自己需要它,我从旧的 SilverSmith 项目中找到了所有这些代码,决定最好不要让它闲置并逐渐消失。希望其他人也能利用这种疯狂。
待办事项
添加一个任务,根据模板生成 PHP 类