更新树枝全局变量的问题

时间:2019-01-08 02:39:42

标签: php twig

您好,我对使用PHP和Twig进行开发还很陌生,并且在更新twig中的全局变量时遇到了问题。如果有一个flash /错误消息全局变量,如果他们输入了错误的输入(例如登录屏幕),我可以向用户显示该变量,那我会很好。

此刻,我正在使用php中的会话获取此Flash消息。更新Flash消息后,也应在Twig中对其进行更新。但是它不会更新,直到我重新加载页面。此时,可以更改Flash消息。我认为问题可能出在PHP中,所以在渲染Twig模板之前,我在代码中回显了flash变量,并且在相应的echo语句中更新了flash变量。我想强调的是,Twig确实更新了Flash消息,但直到页面再次加载后才更新。因此它永远不会显示当前的Flash消息。

我写了一个简短的程序来演示这一点。如果用户按下按钮“一”,则闪现消息应为“消息一”,如果用户按下按钮“二”,则闪现消息应为“消息二”。我在php中包含了Flash消息的回显,在Twig模板中包含了Flash消息。

index.php

<?php
session_start();

require_once '../PhotoBlog/utilities/twig/vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('view');
$twig = new Twig_Environment($loader, array('cache' => false));
$twig->addGlobal('session', $_SESSION);

if (isset($_GET["test_one"])) {
    $_SESSION["flash"] = "message one";
}else if(isset($_GET["test_two"])) {
    $_SESSION["flash"] = "message two";
}
echo "PHP says: ".$_SESSION["flash"]."<br><br>";

echo $twig->render('index.html');


?>

index.html

<form action="index.php" method="GET">
    <input type="submit" name="test_one" value="one">
    <input type="submit" name="test_two" value="two">
</form>

<p>Twig says: {{ session.flash }}</p>

理想情况下,消息应该相互匹配,但是Twig消息始终会打印前一条消息。

但是Twig总是输出倒数第二个提交的内容。我似乎无法解决这个问题。我已经查看了Twig文档和stackoverflow,但未找到任何解决方案。我关闭了缓存,所以我认为我已经排除了这一点,但是也许我在这里遗漏了一些东西。

1 个答案:

答案 0 :(得分:0)

除非在方法的签名中另行指定(PHPfunction addGlobal($key, $value)),否则默认情况下,数组会在function addGlobal($key, &$value) {}中按值传递。

如果您确实想更新即兴消息,则需要切换到一个对象来解决此问题。

<?php

class Foo {
    protected $array = [];

    public function addGlobal($key, $value) {
        $this->array[$key] = $value;
        return $this;
    }

    public function getGlobal($key) {
        return $this->array[$key] ?? null;
    }
}

class Bar {
    protected $value;

    public function setValue($value) {
        $this->value = $value;
        return $this;
    }

    public function getValue() {
        return $this->value;
    }
}

$foo = new Foo();
$bar = new Bar();

$bar->setValue('foobar');
$array = [ 'bar' => 'foobar', ];

$foo->addGlobal('array', $array);
$foo->addGlobal('object', $bar);

$array['bar'] = 'bar';
$bar->setValue('bar');

var_dump($foo->getGlobal('object')->getValue()); /** Output: bar **/
var_dump($foo->getGlobal('array')['bar']); /** Output: foobar **/

demo