需要将“意大利面代码”脚本转换为枝条。阅读Twig文档并获得基本工作。但是,我需要关于如何正确执行所有操作的建议,因此以后不需要重新转换。比方说,当前的脚本看起来如下:将意大利面代码转换为枝条
index.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应该是这样的转变时以嫩枝:
<?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>
如果我理解正确的,它也有可能为 “包括” 在枝杈模板功能(带一些在模板中调整),所以我不需要重写像display_dropdown()
这样的现有PHP函数。因为目前没有显示下拉列表...
有关我的事情是带变量的数组(传递给Twig render
函数)。在Twig可以工作之前,我是否会错过某些东西,或者是否真的需要手动定义每个变量(如$page_message
和$footer_text
)?
这似乎有很多工作要做,因为在“意大利面代码”中,如果我在某处定义了变量,我可以随时通过使用echo
函数来访问它。现在,它看起来我需要查看PHP代码中存在的每个变量,并手动将它传递给Twig参数数组。真?
感谢您的输入。我现在没有迫切需要使用Symfony框架,但是将当前脚本转换为Twig确实已经发挥了重要作用。 –