需要將「意大利麪代碼」腳本轉換爲枝條。閱讀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確實已經發揮了重要作用。 –