php smarty模板引擎實用技巧

來源:互聯網
上載者:User
  1. {capture name="test"}
  2. {/capture}
  3. {$smarty.capture.test}
複製代碼

說明:在{capture name="test"}和{/capture}之間的內容被儲存到變數$test中,該變數由name屬性指定.在模板中通過 $smarty.capture.test 訪問該變數.如果沒有指定name 屬性,函數預設將使用"default" 作為參數,這一點類似Jquery中的clone方法。

二,config_load標籤config_load可以直接將檔案中的內容讀取出來,這樣可以省掉assign這一步。例子:test.csv 檔案:

  1. pageTitle = "config_load_test"
  2. bodyBgColor = "#eeeeee"
  3. img = "girl.jpg"
  4. width="100"
  5. height="100"
複製代碼

則模板 index.tpl 檔案中可以如下引用以上 test.csv 檔案:

  1. {config_load file="test.csv"}
  2. {#pageTitle#}
複製代碼

註:上述過程中如果出現這樣的問題Warning: Smarty error: unable to read resource, 請查看一下,你的test.csv是不是放在smarty的配置目錄中,預設配置目錄是configs 目錄。

三,php標籤

習慣了assign後,有沒有想過,在模板檔案裡面直接寫php代碼呢,雖然非常不建議這麼做,但有時候迫於業務的需求不得不這樣乾的時候該腫麼辦呢?看看下面這個例子:

  1. {php}
  2. global $result;
  3. foreach($result as $key=>$value){
  4. echo "key=$key,value=>$value
    ";
  5. }
  6. {/php}
複製代碼

四,strip標籤strip標籤的作用是去除標籤內的空格和斷行符號,我自己感覺這個標籤還是挺有用的,可以壓縮最終輸出的html格式,想要看效果的話,看看本站的原始碼就知道了,是不是很酷,呵呵:

  1. {strip}
  2. strip
  3. php smarty strip 壓縮html輸出,www.phpernote.com 看源碼效果
  4. {/strip}
複製代碼

五,fetch標籤fetch標籤和php裡面的函數 file_get_contents 功能差不多,都可以把檔案中的內容讀出來,並且可以將讀出來的結果以字串的形式賦值給某個變數,如下使用案例:

  1. {fetch file="./aaaa.txt" assign="result"}
  2. {if is_array($result)}
  3. is array
  4. {else if}
  5. not array
  6. {/if}
複製代碼

六,使用常量

在php中使用 define 定義的常量可以在smarty模板中直接使用使用方法:{$smarty.const.你定義的常量名}

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.