开发者

Mustache partials using variable syntax (without the ">")?

开发者 https://www.devze.com 2023-03-19 06:30 出处:网络
I\'m using开发者_运维知识库 mustache (php version) as my templating engine. I\'m wondering if it\'s possible to have {{something}} serve as a partial, instead of having to format it as {{>something}}

I'm using开发者_运维知识库 mustache (php version) as my templating engine.

I'm wondering if it's possible to have {{something}} serve as a partial, instead of having to format it as {{>something}} in the template. Ideally, a variable would be treated as a partial if the variable name is in the _partials array.

This would allow me to change a variable to a partial without having to make any changes to templates.

Is this possible?


I figured out how to do this by modifying the _renderTag function in Mustache.php. In the switch statement, for the default case, I just check to see if $tag_name is in the $this->_partials array.

protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
    switch ($modifier) {
        case '=':
            return $this->_changeDelimiter($tag_name, $leading, $trailing);
            break;
        case '!':
            return $this->_renderComment($tag_name, $leading, $trailing);
            break;
        case '>':
        case '<':
            return $this->_renderPartial($tag_name, $leading, $trailing);
            break;
        case '{':
            // strip the trailing } ...
            if ($tag_name[(strlen($tag_name) - 1)] == '}') {
                $tag_name = substr($tag_name, 0, -1);
            }
        case '&':
            if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
                return $this->_renderEscaped($tag_name, $leading, $trailing);
            } else {
                return $this->_renderUnescaped($tag_name, $leading, $trailing);
            }
            break;
        case '#':
        case '^':
        case '/':
            // remove any leftover section tags
            return $leading . $trailing;
            break;
        default:
            // Render var as partial if it is in _partial array (so we don't have to use "{>partial}" syntax)
            if ($this->_partials[$tag_name]) {
                $partial = $this->_renderPartial($tag_name, $leading, $trailing);
                return $partial;
            }


            if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
                return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
            } else {
                return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
            }
            break;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号