php - 如何检测 Silverstripe 页面作为父级还是子级加载到 Controller 中

标签 php silverstripe

我们的 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 对象。检索 DataObjectsDataList 时,仅加载它们的类,而不加载它们的 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/

相关文章:

php - 静态插入后的 Doctrine 增量 id

php - $_GET URL 来自 ?url=http ://google. com

php - 从一串php中获取特定的值

php - 我如何在 SilverStripe 3.1 中按字母顺序排序(但大写字母不是小写字母之前的一组)?

php - 从输入 [] 获取数据时从 PDO 中的数组重复插入时循环困惑

php - 计算哪个位置是我的图片,因为索引和数组

php - Silverstripe UserForms - 从 DataObject 填充选项

javascript - SilverStripe/Entwine Hook 操作保存按钮

silverstripe - 可选的 OptionsetField 是 SilverStripe 3.2

仅限 SilverStripe 框架 - 如何处理 404