Công cụ thành viên

Công cụ trang web


programming4:template-engine

Đây là một phiên bản cũ của tài liệu!


PHP Template Engine

Ở các phiên bản trước NukeViet 4.4 chúng tôi sử dụng Xtemplate để tách html và PHP

Từ phiển bản 4.4 Chúng tôi xây dựng giao diện mới dựa trêm Smarty, và chuyển dần từ Xtemplate sang Smarty 3

Tài liệu hướng dẫn sử dụng Smarty 3: https://www.smarty.net/docs/en/

Chuyển đổi cách viết từ Xtemplate sang Smarty

Với Xtemplate code PHP

    $xtpl = new XTemplate($layout_file, NV_ROOTDIR . '/themes/' . $global_config['module_theme'] . '/layout');
 
    $xtpl->assign('MODULE_CONTENT', $contents);    
    return $xtpl->text('main');

Chuyển sang Smarty

    $smarty = new Smarty();
    $smarty->setTemplateDir(NV_ROOTDIR . '/themes/' . $global_config['module_theme'] . '/layout');
 
    $smarty->assign('MODULE_CONTENT', $contents);        
    return $smarty->fetch($layout_file);

Với Xtemplate code HTML

<!-- BEGIN: main -->
{FILE "header_only.tpl"}
	{MODULE_CONTENT}
{FILE "footer_only.tpl"}
<!-- END: main -->

Chuyển sang Smarty

{include file='header_only.tpl'} 
{$MODULE_CONTENT}
{include file='footer_only.tpl'}

Xử lý xòng lặp dữ liệu

Giả sử có mảng dữ liệu muốn xuất ra html

$contacts = array(
        array(
            "phone" => "1",
            "fax" => "2",
            "cell" => "3"
        ),
        array(
            "phone" => "555-4444",
            "fax" => "555-3333",
            "cell" => "760-1234"
        )
    );

Với Xtemplate code PHP

foreach ($contacts as $row) {
    $xtpl->assign('ROW', $row);
    $xtpl->parse('main.loop');
}

Với Xtemplate code HTML

<!-- BEGIN: main -->
<!-- BEGIN: loop -->
        <br>
        phone: {ROW.phone}
        <br>
            fax: {ROW.fax}
        <br>
            cell: {ROW.cell}
        <br>
<!-- END: loop -->
<!-- END: main -->

Chuyển sang Smarty code PHP

$smarty->assign("contacts",$contacts);

Chuyển sang Smarty code HTML

    {section name=sec1 loop=$contacts}
        <br>
        phone: {$contacts[sec1].phone}
        <br>
 
            fax: {$contacts[sec1].fax}
        <br>
 
            cell: {$contacts[sec1].cell}
        <br>
    {/section}
 

Một số phương thức định dạng cơ bản

Ví dụ biến {$tile} Trong template cần xử lý ta có thể xử lý như sau:

{$tile|upper} viết hoa $itle

{$tile|lower} viết thường $itle

{$tile|capitalize} viết hoa đầu từ $itle

{$tile|strip_tags} Định dạng bỏ kí tự đặc biệt $itle

{$date|date_format} Định dạng ngày thàng $ate

Ngoài các ví dụ trên smarty còn hỗ trợ các phương thức xử lý biến sau:

capitalize
cat
count_characters
count_paragraphs
count_sentences
count_words
date_format
default
escape
from_charset
indent
lower
nl2br
regex_replace
replace
spacify
string_format
strip
strip_tags
to_charset
truncate
unescape
upper
wordwrap
programming4/template-engine.1524038141.txt.gz · Sửa đổi lần cuối: 2018/04/18 14:55 bởi vuthao