1

在将变量分配给视图时获得一致的行为时遇到问题。例如:

在控制器中:

$this->view->media = Media::findFirst(['groupId=0', 'order' => 'RAND()', 'limit' => 1]);

鉴于:

        {% if media is defined %}
        <div class="thumbnail">
            <img src="{{ static_url('img/media/thumbs/' ~ media.name) }}" class="img-round">
            <div class="caption">
                <h3>{{ media.title }}</h3>
                <p>{{ media.description }}</p>
            </div>
        </div>
        {% endif %}

解析如下:

        <?php if (isset($media)) { ?>
        <div class="thumbnail">
            <img src="<?php echo $this->url->getStatic('img/media/thumbs/' . $this->media->name); ?>" class="img-round">
            <div class="caption">
                <h3><?php echo $this->media->title; ?></h3>
                <p><?php echo $this->media->description; ?></p>
            </div>
        </div>
        <?php } ?>

问题是当模板的解析版本时,$media 无法通过 $this 访问,因此 isset($media) 通过,但对 $this->media 的引用什么也不返回。

有什么方法可以强制 $media 在范围内是本地的?

4

1 回答 1

0

I think I got it.

Misbehaviour description

You have probably declared a media module in your DI(). I was trying quite a lot to reproduce that error, and got it finally when i set a dumb media service among configuration files:

$di->set('media', function() {
    return new \stdClass();
});

and than got the same behavior you have - Volt during compilation is not sure, what variable to use and choses $this->media (DI::get('media')) instead of $media or $this->view->media var for obtaining data.

Solution

If you dont want to resign from calling you findFirst result under that variable name, you may bypass that by using View in volt directly:

{% if view.media is defined %}
    <div class="thumbnail">
        <img src="{{ static_url('img/media/thumbs/' ~ view.media.name) }}" class="img-round">
        <div class="caption">
            <h3>{{ view.media.title }}</h3>
            <p>{{ view.media.description }}</p>
        </div>
    </div>
{% endif %}

it will generate $this->view->media calls instead of $this->media ones.

+1 on that question.

于 2015-03-06T12:34:29.983 回答