2

我正在尝试为我的模板创建宏,如下所示:

{%- macro bField(form, name, attributes) %}
    <p class="form-group" ng-class="{has-error: !{{ form.name }}.{{ name }}.$valid}">
        {{ form.label(name) }}
        {#{% set attributes['class'] = 'form-control' %}#}
        {{ form.render(name, attributes) }}
        {% include 'forms/validation-messages.volt' %}
    </p>
{%- endmacro %}

问题是它位于视图根目录中的 macros.volt 文件中,我不知道如何或在何处包含它,因此它随处可用。我尝试使用包含和部分功能的根布局(index.volt),但仍然无法正常工作。即使在模板文件中我也没有尝试使用它。我做错了什么,如何解决这个问题?

另一件事是如何为数组中的某个键设置值。我显然尝试过{% set attributes['class'] = 'form-control' %},但它不起作用。

4

1 回答 1

6

很棒的解决方案,在Phalcon 论坛上找到。根据我的情况定制了一点。

建议是扩展 Volt 引擎类,然后在\Phalcon\Mvc\View\Engine\Volt::getCompiler.

// extended class to load the macros before parse time
class VoltC extends \Phalcon\Mvc\View\Engine\Volt
{
    public function getCompiler()
    {
      if (empty($this->_compiler))
      {
        parent::getCompiler();

        // add macros that need initialized before parse time
        $this->partial("macros/form");
      }

      return parent::getCompiler();
    }
}
$di->set("voltEngine", function( $view, $di ){
    $volt = new VoltC($view, $di);

    $volt->setOptions(array(
        "compiledPath" => "../app/tmp/cache/",
        "compiledExtension" => ".cmp",
        'compileAlways' => true
    ));

    return $volt;
});
于 2013-11-02T19:18:44.263 回答