Silverstripe - 是否可以在include语句中使用变量?

时间:2013-08-21 15:25:14

标签: templates variables include silverstripe

我正在使用silverstripe模板,我想循环遍历当前页面的子页面,并根据该子页面的类型在'include'控件中动态输入模板名称。

这是我到目前为止的代码:

    <div id="tertiary-content">                   
        <% if $Children %>
            <% loop $Children %>
                <% include $ClassName %>
            <% end_loop %>
        <% end_if %>
    </div>

(我的模板中有ss文件/包含与$ ClassName变量相关的目录)

这是我得到的错误:

错误是:遇到未知的打开块“循环”。也许你错过了结束标签或错误拼写了它?

我在silverstripe论坛上发现了这篇文章,这让我认为它应该有效: http://www.silverstripe.org/archive/show/1023

实际上是否可以在include控件中包含变量?

3 个答案:

答案 0 :(得分:7)

您可以在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>

答案 1 :(得分:4)

您可以直接从模板中调用renderWith,例如:

<div id="tertiary-content">                   
    <% if $Children %>
        <% loop $Children %>
            $renderWith($ClassName)
        <% end_loop %>
    <% end_if %>
</div>

答案 2 :(得分:1)

进行了一些测试但无法使<% include $ClassName %>起作用。但你可以通过以下方式解决这个问题:

<% if $ClassName = 'SomeClass' %>
    <% include SomeClass %> 
<% else_if $ClassName = 'SomeOtherClass' %>
    <% include SomeOtherClass %>
<% else %>
    <% include DefaultClass %>
<% end_if %>

不是那么漂亮,但能胜任。

相关问题