- 创建模板
在看小胡子模板编译之前 我们需要看一下是哪里把变量发送给他然后叫他渲染的;
首先我们会在local/pluginname下面创建一个classes的文件夹,然后接着在classes下创建output文件夹 然后像我一样创建处理数据的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) { // 实例会被默认调用
$this->sometext = $sometext;
}
/**
* Export this data so it can be used as the context for a mustache template.
* 导出此数据,以便将其用作胡子模板的上下文。
* @return stdClass
*/
public function export_for_template(renderer_base $output) {
global $PAGE;
$data = new stdClass();
$data->list = ['张三','李四','王二麻子','刘老根','钢铁侠','蜘蛛精','王小蒙','凹凸曼'];
$data->sometext = $this->sometext;
return $data; // 数据对象
}
}
- 创建渲染器
同目录下创建 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); // 取到刚刚的模板数据
return parent::render_from_template('local_wxpay/index_page', $data); // 进行小胡子模板渲染
//local_wxpay/index_page :"插件名字/渲染模板(就是小胡子模板)" 对比下面的目录你就会发现
}
}
-
加载模板
渲染器和渲染模板都已经编写完成。然后呢????? 去使用它(渲染器)
-
添加小胡子模板
// local/wxpay/templates/index_page.mustache
// 渲染变量
{{!
@template local_wxpay/index_page
}}
<div class="hero-unit">
<button class="pay">加入会员,充值0元返999,你值得拥有</button>
<p>{{sometext}}</p>
{{data}}
{{#list}} // 循环这个list (这是个数组 想要取得每一项就需要用{{.}})
<p>时尚大咖::{{.}}</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); // 设置当前路径
$PAGE->set_title($title); // 标题
$PAGE->set_pagelayout('standard');// 常用布局
$PAGE->set_heading($title);
$PAGE-> set_context (context_system :: instance ()); // 上下文
$renderable = new \local_wxpay\output\index_page('可喜可贺可喜可贺啊');
// 通过命名空间找到index_page这个对象
// 上面的sometext 等同于 “可喜可贺可喜可贺啊”
$PAGE->navbar->add($title, $url); // 头部导航
echo $OUTPUT->header();
echo $OUTPUT->heading($pagetitle);// 页面标题
$output = $PAGE->get_renderer('local_wxpay');
echo $OUTPUT->render($renderable);// 执行output文件夹下renderer函数
echo $OUTPUT->footer();
如果觉得有帮助 请给小编一个star
你的star✨、点赞和关注是我持续创作的动力!
网友评论