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

问题描述 投票:3回答:3

我正在使用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控件中包含变量?

templates variables include silverstripe
3个回答
1
投票

做了一些测试,无法让<% include $ClassName %>工作。但你可以通过以下方式解决这个问题:

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

不是那么漂亮,但做的工作。


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>

4
投票

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

<div id="tertiary-content">                   
    <% if $Children %>
        <% loop $Children %>
            $renderWith($ClassName)
        <% end_loop %>
    <% end_if %>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.