SilverStripe 覆盖模板 SS3.1.10

SilverStripe Overiding Template SS3.1.10

我正在尝试根据图像大小覆盖页面模板。当我用 ?showtemplate 检查管道时,它说正在渲染正确的模板,但实际上它是默认模板。我的控制器如下

class Artwork_Controller extends Page_Controller {

    private static $allowed_actions = array (
    );

    public function init() {
        parent::init();

        $image = $this->OrderedImages()->first();

        if($image && $ratio = $image->getRatio()) {

            if($ratio > 1.2 ) {
                $this->renderWith("ArtworkWide");
            } elseif ($ratio < 0.8) {
                $this->renderWith("ArtworkNarrow");
            } else {
                $this->renderWith("Artwork");
            }

        }

    }

}

如果我将 Debug 注入它在页面上呈现的 if 块,那么它会正确调用。但是在管道的最后一点被覆盖

ViewableData::renderWith() returns 一个 HTMLText 对象,您什么都不做。

SilverStripe 不会像 CodeIgniter 那样随意抽取数据输出。

您要找的是:

public function index() { //this is important - do not perform this in init!

    $image = $this->OrderedImages()->First();
    $ratio = $image->Ratio;

    if($ratio > 1.2) $layoutTemplate = 'ArtworkWide';
    if($ratio < 0.8) $layoutTemplate = 'ArtworkNarrow';

    //the array/second element is redundant if your template is a 'main' template, not a 'Layout' one.
    return $image ? $this->renderWith([$layoutTemplate, Page]) : $this; 
}