Templates Silverstripe-是否可以在include语句中使用变量?
我正在使用silverstripe模板,我想循环当前页面的子页面,并根据子页面类型在“include”控件中动态输入模板名称 以下是我目前掌握的代码:Templates Silverstripe-是否可以在include语句中使用变量?,templates,variables,include,silverstripe,Templates,Variables,Include,Silverstripe,我正在使用silverstripe模板,我想循环当前页面的子页面,并根据子页面类型在“include”控件中动态输入模板名称 以下是我目前掌握的代码: <div id="tertiary-content"> <% if $Children %> <% loop $Children %> <% include $ClassName %>
<div id="tertiary-content">
<% if $Children %>
<% loop $Children %>
<% include $ClassName %>
<% end_loop %>
<% end_if %>
</div>
(我的templates/Includes目录中有与$ClassName变量相关的ss文件)
下面是我得到的错误:
错误为:遇到未知的开放块“循环”。可能是您遗漏了结束标记或拼写错误?
我在一个silverstripe论坛上找到了这篇文章,这让我觉得它应该可以工作:
实际上是否可能在包含控件中包含变量?进行了一些测试,但无法使
正常工作。但你可以用以下方法来解决这个问题:
<% if $ClassName = 'SomeClass' %>
<% include SomeClass %>
<% else_if $ClassName = 'SomeOtherClass' %>
<% include SomeOtherClass %>
<% else %>
<% include DefaultClass %>
<% end_if %>
没有那么漂亮,但是可以完成任务。您可以在Page类中编写一个函数,根据当前类名加载ss模板。在Page.php文件中
class Page extends SiteTree {
/**
* Returns a template based on the current ClassName
* @return {mixed} template to be rendered
**/
public function getIncludeTemplate(){
return $this->renderWith($this->ClassName);
}
}
然后在你的模板中
<div id="tertiary-content">
<% if $Children %>
<% loop $Children %>
$IncludeTemplate
<% end_loop %>
<% end_if %>
</div>
$IncludeTemplate
您可以直接从模板调用renderWith
,例如:
<div id="tertiary-content">
<% if $Children %>
<% loop $Children %>
$renderWith($ClassName)
<% end_loop %>
<% end_if %>
</div>
$renderWith($ClassName)
我不知道Silverstripe的用法,但在php中可以使用变量作为include。虽然includes通常带有“”。Silverstripe使用自己的模板系统,而这实际上是不使用php的模板(.ss文件),我还尝试将$ClassName变量放入{}中,但这给了我同样的错误。这就是我目前解决问题的方法,我希望使它更具动态性,这样如果我们想在将来添加另一种页面类型,就不必修改此代码来解释它。这绝对是解决问题的一种方法,谢谢!我非常确定在加载页面时会调用renderWith(),并且我正在使用jquery加载子内容。标记因为这是一个很好的解决方案如果我没有用jQuery隐藏/显示内容如果您使用jQuery加载子内容,那么我假设您是通过AJAX加载内容?如果是这样,那么返回JSON/HTML/etc的控制器方法可以对子对象类型进行此测试,并返回适当的输出。