如何检测银条页面是否作为父级或子级加载到控制器中


How to detect Silverstripe page is loaded in Controller as parent or child

我们的 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 %>

我想确保如果有人不小心链接到一个部分,它会重定向到父多部分页面。

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,使用此方法也会触发重定向,因为每次呈现 Section DataObject 时都必须调用 init。

如何检测部分控制器是作为独立的父级(重定向)还是作为多节页面的子级加载?

查看

MultiSectionPage时不应调用Section_Controller。循环遍历 PageSections 时仅加载 Section 对象。检索DataList DataObjects时,仅加载其类,而不加载其控制器。

请注意,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);
    }
}