【发布时间】:2017-04-20 14:17:13
【问题描述】:
需要将带有“意大利面条代码”的脚本转换为 Twig。阅读 Twig 文档并获得基础知识。但是,我需要有关如何正确执行所有操作的建议,因此以后不需要重新转换。假设当前脚本如下所示:
文件索引.php:
<?php
$page_message="do it";
function display_dropdown($max)
{
for ($i=0; $i<$max; $i++)
{
echo "<option value='$i'>Option $i</option>";
}
}
?>
<!DOCTYPE html>
<html>
<body>
<h1><?php echo $page_message; ?></h1>
<form method="post" action="<?php echo basename($_SERVER["SCRIPT_FILENAME"]); ?>">
<select name="whatever"><?php display_dropdown(10); ?></select>
<input type="submit" value="go">
<?php include("footer.php");?>
</body>
</html>
footer.php 看起来:
<?php
$footer_text="blah blah";
?>
<footer><?php echo $footer_text; ?></footer>
据我了解,我的 index.php 转换为 Twig 后应该是这样的:
<?php
$page_message="do it";
function display_dropdown($max)
{
for ($i=0; $i<$max; $i++)
{
echo "<option value='$i'>Option $i</option>";
}
}
$twig_params_array=array("page_message"=>$page_message, "footer_text"=>"blah blah");
require_once("../lib/Twig/Autoloader.php");
Twig_Autoloader::register();
$loader=new Twig_Loader_Filesystem("templates");
$twig=new Twig_Environment($loader);
echo $twig->render("index_template.html", $twig_params_array);
?>
然后我应该使用以下代码创建index_template.html 和footer_template.html(或其他):
index_template.html
<!DOCTYPE html>
<html>
<body>
<h1>{{ page_message }}</h1>
<form method="post" action="{{ _self }}>">
<select name="whatever"><?php display_dropdown(10); ?></select>
<input type="submit" value="go">
{{ include('footer_template.html') }}
</body>
</html>
footer_template.html
<footer>{{ footer_text }}</footer>
如果我理解正确,也可以在 Twig 模板中“包含”函数(在模板中进行一些调整),所以我不需要重写现有的 PHP 函数,如 display_dropdown()。因为下拉菜单暂时没有显示...
我关心的是带有变量的数组(传递给 Twig render 函数)。我错过了什么,还是真的需要在 Twig 工作之前手动定义每个变量(如$page_message 和$footer_text)?
这似乎有很多工作要做,因为在“意大利面条代码”中,如果我在某处定义变量,我可以随时使用echo 函数访问它。现在,看起来我需要查看 PHP 代码中存在的每个变量,并手动将其传递给 Twig 参数数组。真的吗?
【问题讨论】: