我们的 Silverstripe 项目有以下两种页面类型:
class MultiSectionPage extends Page {
private static $allowed_children = array(
'Section'
);
public function PageSections() {
$PageSections = Section::get()->filter(array('ParentID' => $this->ID));
return $PageSections;
}
}
class Section extends Page {
public static $allowed_children = array();
private static $show_in_sitetree = false;
}
在 Layout/MultiSectionPage.ss 模板中,以下代码将每个子节作为数据对象循环:
<% loop $PageSections %>
<% include MultiSectionPage_Section %>
<% end_loop %>
我想确保如果有人不小心链接到某个部分,它会重定向到父 MultiSectionPage。
class Section extends Page {
public function Link() {
return parent::Link() . '#section-' . $this->ID;
}
}
class Section_Controller extends Page_Controller {
public function init(){
parent::init();
if(!$this->getResponse()->isFinished() && $link = $this->Link()) {
$this->redirect($link, 301);
return;
}
}
}
但是,即使在查看 MultiSectionPage 时,使用此方法也会触发重定向,因为每次呈现部分数据对象时都必须调用 init。
如何检测部分 Controller 是作为独立父级(重定向)还是作为 MultiSectionPage 的子级加载?
最佳答案
查看 MultiSectionPage
时,不应调用 Section_Controller
。循环访问 PageSections
时,仅加载 Section
对象。检索 DataObjects
的 DataList
时,仅加载它们的类,而不加载它们的 Controller 。
请注意,Section_Controller
应重定向到父页面链接,而不是当前页面链接。我还建议更新 Section
Link
函数以返回父链接:
class Section extends Page {
private static $allowed_children = array();
private static $show_in_sitetree = false;
public function Link($action = null) {
return $this->Parent()->Link($action);
}
}
class Section_Controller extends Page_Controller {
public function init() {
parent::init();
return $this->redirect($this->Parent()->Link(), 301);
}
}
关于php - 如何检测 Silverstripe 页面作为父级还是子级加载到 Controller 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339708/