2012-10-18 28 views
0

我知道這是主觀的第一部分,但我想聽聽人們使用的一些不同的技術。這是一個兩部分問題:你在PHP中對複雜的多行字符串使用什麼?而且,我可以使用與smarty合成類型的關係嗎?鏈接smarty模板和乾淨的多行字符串 - PHP

問題1:我知道有heredoc和「。」運營商。如果有任何問題,我正在尋找新的,更具可讀性的想法。

問題2:更具體地說,這裏是我想用smarty做的事情。

說我有一個模板,base.tpl:

<html> 
<head><title></title></head> 
<body> 
{$main_content} 
</body> 
</html> 

我可以連模板,即代表$ main_content另一個模板,說main.tpl:

<div id="header">$header</div> 
<div id="container"> 
<h1>{$first_header}</h1> 
<p>{$first_paragraph}</p> 
<h1>{$second_header}</h1> 
<p>{$second_paragraph}</p> 

我想在任何.php加載一個模板到另一個,所以即:

// ... including smarty and all other boiler plate things ... 

$smarty -> assign('first_header', "Foo"); 
$smarty -> assign('first_paragraph', "This is a paragraph"); 
$smarty -> assign('second_header', "Bar"); 
$smarty -> assign('second_paragraph', "This is another paragraph"); 

$main_content = $smarty->load('main.tpl'); 
$smarty -> display('base.tpl'); 

我知道有「模板inheritanc e「,但我並不熟悉它。它可以給我類似的功能嗎?

注:我認爲我與heredoc最大的問題是,我無法得到HTML的語法高亮(如果我在heredoc字符串中指定html)。如果沒有突出顯示,我想通過smarty閱讀的html更難以閱讀,這種打破smarty的目的。

+0

你的模板看起來不合法....似乎缺少''''和'}'? – Baba

+0

對不起,我剛剛通過一個例子,我是新來的聰明。我會修復它,雖然 – clementine

+0

我的答案在模板中包含模板方面有意義嗎? –

回答

2

您將要使用{include}在模板中調用模板(片段)。

http://www.smarty.net/docsv2/en/language.function.include.tpl

<html> 
<head> 
    <title>{$title}</title> 
</head> 
<body> 
{include file='page_header.tpl'} 

{* body of template goes here, the $tpl_name variable 
    is replaced with a value eg 'contact.tpl' 
*} 
{include file="$tpl_name.tpl"} 

{include file='page_footer.tpl'} 
</body> 
</html> 

變量傳遞到包括模板:

{include file='links.tpl' title='Newest links' links=$link_array} 
{* body of template goes here *} 
{include file='footer.tpl' foo='bar'} 

在多行字符串而言,我傾向於使用這種模式:

$my_string = "Wow, this is going to be a long string. How about " 
      . "we break this up into multiple lines? " 
      . "Maybe add a third line?"; 

至於你說的,這是主觀的。不管你覺得舒服,並且只要它的易於閱讀...

0

我發現今天早上模板繼承的一些文件...

要在上面我舉的例子擴展,你可以有一個基地佈局(基地.tpl)

<html> 
<head><title>{$title|Default="title"}</head> 

<body> 

<nav>{block name=nav}{/block}</nav> 

<div id="main">{block name=main}Main{/block}</div> 

<footer>Copyright information blah blah...</footer> 

</body> 
</html> 

可以擴展模板,並使用新版本的Smarty(home.tpl)

{extends file=base.tpl} 

{block name=nav} 
      <ul style="list-style:none"> 
      {foreach $links as $link} 
       <li><a href="{$link.href}" target="_blank">{$link.txt}</a></li> 
      {/foreach} 
      </ul> 
{/block} 

{block name=main} 
    {foreach $paragraphs as $p} 
     <h2>{$p.header}</h2> 
     <p>{$p.content}</p> 
    {/foreach} 
{/block} 

現在覆蓋塊0