- 創(chuàng)建模板
在看小胡子模板編譯之前 我們需要看一下是哪里把變量發(fā)送給他然后叫他渲染的磕谅;
首先我們會(huì)在local/pluginname下面創(chuàng)建一個(gè)classes的文件夾叔扼,然后接著在classes下創(chuàng)建output文件夾 然后像我一樣創(chuàng)建處理數(shù)據(jù)的php文件;
直接lu代碼
// 目錄 : local/wxpay/classes/output/index_page.php
<?php
namespace local_wxpay\output; // 命名空間
use renderable;
use renderer_base;
use templatable;
use stdClass;
class index_page implements renderable, templatable {
var $sometext = null; // 自PHP 5.3起脂新,var已被棄用厌漂,并且是“public”的同義詞。
public function __construct($sometext) { // 實(shí)例會(huì)被默認(rèn)調(diào)用
$this->sometext = $sometext;
}
/**
* Export this data so it can be used as the context for a mustache template.
* 導(dǎo)出此數(shù)據(jù)章咧,以便將其用作胡子模板的上下文。
* @return stdClass
*/
public function export_for_template(renderer_base $output) {
global $PAGE;
$data = new stdClass();
$data->list = ['張三','李四','王二麻子','劉老根','鋼鐵俠','蜘蛛精','王小蒙','凹凸曼'];
$data->sometext = $this->sometext;
return $data; // 數(shù)據(jù)對(duì)象
}
}
- 創(chuàng)建渲染器
同目錄下創(chuàng)建 renderer.php
<?php
namespace local_wxpay\output;
defined('MOODLE_INTERNAL') || die;
use plugin_renderer_base;
class renderer extends plugin_renderer_base {
public function render_index_page($page) {
$data = $page->export_for_template($this); // 取到剛剛的模板數(shù)據(jù)
return parent::render_from_template('local_wxpay/index_page', $data); // 進(jìn)行小胡子模板渲染
//local_wxpay/index_page :"插件名字/渲染模板(就是小胡子模板)" 對(duì)比下面的目錄你就會(huì)發(fā)現(xiàn)
}
}
加載模板
渲染器和渲染模板都已經(jīng)編寫(xiě)完成卤档。然后呢劝枣?溪胶?哗脖?扳还?桑逝? 去使用它(渲染器)
添加小胡子模板
// local/wxpay/templates/index_page.mustache
// 渲染變量
{{!
@template local_wxpay/index_page
}}
<div class="hero-unit">
<button class="pay">加入會(huì)員楞遏,充值0元返999,你值得擁有</button>
<p>{{sometext}}</p>
{{data}}
{{#list}} // 循環(huán)這個(gè)list (這是個(gè)數(shù)組 想要取得每一項(xiàng)就需要用{{.}})
<p>時(shí)尚大咖::{{.}}</p>
{{/list}}
</div>
- 模板方法
// local/wxpay/index.php
// 廢話不多講 我們就披沙揀金
<?php
require_once(dirname(__FILE__) . '/../../config.php');
require_login();
$title = get_string('pluginname', 'local_wxpay');
$pagetitle = $title;
$url = new moodle_url("/local/wxpay/index.php");
$PAGE->set_url($url); // 設(shè)置當(dāng)前路徑
$PAGE->set_title($title); // 標(biāo)題
$PAGE->set_pagelayout('standard');// 常用布局
$PAGE->set_heading($title);
$PAGE-> set_context (context_system :: instance ()); // 上下文
$renderable = new \local_wxpay\output\index_page('可喜可賀可喜可賀啊');
// 通過(guò)命名空間找到index_page這個(gè)對(duì)象
// 上面的sometext 等同于 “可喜可賀可喜可賀啊”
$PAGE->navbar->add($title, $url); // 頭部導(dǎo)航
echo $OUTPUT->header();
echo $OUTPUT->heading($pagetitle);// 頁(yè)面標(biāo)題
$output = $PAGE->get_renderer('local_wxpay');
echo $OUTPUT->render($renderable);// 執(zhí)行output文件夾下renderer函數(shù)
echo $OUTPUT->footer();
如果覺(jué)得有幫助 請(qǐng)給小編一個(gè)star
你的star?撬陵、點(diǎn)贊和關(guān)注是我持續(xù)創(chuàng)作的動(dòng)力!