基本树枝,'updating' 模板

basic twig, 'updating' template

我是 php 和 twig 的新手,所以如果这些问题听起来很愚蠢,请不要生气 ;)

我正在系树枝和纽扣。我想做的事: 变量 $num 为 1,在模板中显示为 {{ num }},如下所示:

1
[更改值]

用户单击一个按钮(名为 "change value")将 1 添加到 $num(所以现在 $num 是 2)。模板现在应该更新并显示“2”,如下所示:

2
[更改值]

用户再次点击它的 3 以此类推...

我的申请中发生的事情是: 用户点击按钮,整个 index.html 被添加到第一个,所以现在显示:

1
[更改值]
2
[更改值]

而不仅仅是:

2
[更改值]

在此之后,如果用户再次单击该按钮,则不会发生任何事情。

如何"update"模板中的变量?为什么我只能点击一次按钮?

这是我的 html 代码:

<html>
<body>

<p> {{ tempOne }} </p>

<form action="index.php" method="post">
  <input type="submit" name="submit" value="change value"/>
</form>

</body>
</html>

和我的 php:

<?php

$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password =  '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
$template = $twig->loadTemplate('index.html');

$num = 1;
echo $template->render(array('tempOne' => $num));

if(isset($_POST['submit'])){
    $num = $num + 1;
    echo $template->render(array('tempOne' => $num));
}

将您的 php 代码更改为以下内容:

<?php

$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password =  '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
$template = $twig->loadTemplate('index.html');



if(isset($_POST['submit'])){
    $num = $_POST['num'] + 1;
    echo $template->render(array('tempOne' => $num));
} else {
    $num = 1;
    echo $template->render(array('tempOne' => $num));
}

和HTML到:

<form action="index.php" method="post">
  <input type="hidden" name="num" value="{{tempOne}}"/>
  <input type="submit" name="submit" value="change value"/>
</form>