MDL-64348 template: add load_template_with_dependencies external func

This commit is contained in:
Ryan Wyllie 2018-12-11 11:04:43 +08:00
parent 0664130b88
commit e0034b5da6
4 changed files with 105 additions and 173 deletions

View file

@ -58,15 +58,6 @@ class external extends external_api {
);
}
/**
* Remove comments from mustache template.
* @param string $templatestr
* @return mixed
*/
protected static function strip_template_comments($templatestr) {
return preg_replace('/(?={{!)(.*)(}})/sU', '', $templatestr);
}
/**
* Return a mustache template, and all the strings it requires.
*
@ -84,23 +75,14 @@ class external extends external_api {
'themename' => $themename,
'includecomments' => $includecomments));
$component = $params['component'];
$template = $params['template'];
$themename = $params['themename'];
$includecomments = $params['includecomments'];
$templatename = $component . '/' . $template;
$loader = new mustache_template_source_loader();
// Will throw exceptions if the template does not exist.
$filename = mustache_template_finder::get_template_filepath($templatename, $themename);
$templatestr = file_get_contents($filename);
// Remove comments from template.
if (!$includecomments) {
$templatestr = self::strip_template_comments($templatestr);
}
return $templatestr;
return $loader->load(
$params['component'],
$params['template'],
$params['themename'],
$params['includecomments']
);
}
/**
@ -112,6 +94,95 @@ class external extends external_api {
return new external_value(PARAM_RAW, 'template');
}
/**
* Returns description of load_template_with_dependencies() parameters.
*
* @return external_function_parameters
*/
public static function load_template_with_dependencies_parameters() {
return new external_function_parameters([
'component' => new external_value(PARAM_COMPONENT, 'component containing the template'),
'template' => new external_value(PARAM_ALPHANUMEXT, 'name of the template'),
'themename' => new external_value(PARAM_ALPHANUMEXT, 'The current theme.'),
'includecomments' => new external_value(PARAM_BOOL, 'Include comments or not', VALUE_DEFAULT, false)
]);
}
/**
* Return a mustache template, and all the child templates and strings it requires.
*
* @param string $component The component that holds the template.
* @param string $template The name of the template.
* @param string $themename The name of the current theme.
* @param bool $includecomments Whether to strip comments from the template source.
* @return string the template
*/
public static function load_template_with_dependencies(
string $component,
string $template,
string $themename,
bool $includecomments = false
) {
global $DB, $CFG, $PAGE;
$params = self::validate_parameters(
self::load_template_with_dependencies_parameters(),
[
'component' => $component,
'template' => $template,
'themename' => $themename,
'includecomments' => $includecomments
]
);
$loader = new mustache_template_source_loader();
// Will throw exceptions if the template does not exist.
$dependencies = $loader->load_with_dependencies(
$params['component'],
$params['template'],
$params['themename'],
$params['includecomments']
);
$formatdependencies = function($dependency) {
$results = [];
foreach ($dependency as $dependencycomponent => $dependencyvalues) {
foreach ($dependencyvalues as $dependencyname => $dependencyvalue) {
array_push($results, [
'component' => $dependencycomponent,
'name' => $dependencyname,
'value' => $dependencyvalue
]);
}
}
return $results;
};
// Now we have to unpack the dependencies into a format that can be returned
// by external functions (because they don't support dynamic keys).
return [
'templates' => $formatdependencies($dependencies['templates']),
'strings' => $formatdependencies($dependencies['strings'])
];
}
/**
* Returns description of load_template_with_dependencies() result value.
*
* @return external_description
*/
public static function load_template_with_dependencies_returns() {
$resourcestructure = new external_single_structure([
'component' => new external_value(PARAM_COMPONENT, 'component containing the resource'),
'name' => new external_value(PARAM_TEXT, 'name of the resource'),
'value' => new external_value(PARAM_RAW, 'resource value')
]);
return new external_single_structure([
'templates' => new external_multiple_structure($resourcestructure),
'strings' => new external_multiple_structure($resourcestructure)
]);
}
/**
* Returns description of load_icon_map() parameters.
*

View file

@ -1396,6 +1396,14 @@ $functions = array(
'loginrequired' => false,
'ajax' => true,
),
'core_output_load_template_with_dependencies' => array(
'classname' => 'core\output\external',
'methodname' => 'load_template_with_dependencies',
'description' => 'Load a template and its dependencies for a renderable',
'type' => 'read',
'loginrequired' => false,
'ajax' => true,
),
'core_output_load_fontawesome_icon_map' => array(
'classname' => 'core\output\external',
'methodname' => 'load_fontawesome_icon_map',

View file

@ -1,147 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for lib/classes/output/external.php
* @author Guy Thomas <gthomas@moodlerooms.com>
* @copyright Copyright (c) 2017 Blackboard Inc.
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
use core\output\external;
require_once(__DIR__.'/../../lib/externallib.php');
require_once(__DIR__.'/../../lib/mustache/src/Mustache/Tokenizer.php');
require_once(__DIR__.'/../../lib/mustache/src/Mustache/Parser.php');
/**
* Class core_output_external_testcase - test \core\output\external class.
* @package core
* @author Guy Thomas <gthomas@moodlerooms.com>
* @copyright Copyright (c) 2017 Blackboard Inc.
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_output_external_testcase extends base_testcase {
/**
* Ensure that stripping comments from templates does not mutilate the template body.
*/
public function test_strip_template_comments() {
$templatebody = <<<'TBD'
<h1>{{# str }} pluginname, mod_lemmings {{/ str }}</h1>
<div>{{test}}</div>
<div>{{{unescapedtest}}}</div>
{{#lemmings}}
<div>
<h2>{{name}}</h2>
{{> mod_lemmings/lemmingprofile }}
{{# pix }} t/edit, core, Edit Lemming {{/ pix }}
</div>
{{/lemmings}}
{{^lemmings}}Sorry, no lemmings today{{/lemmings}}
<div id="{{ uniqid }}-tab-container">
{{# tabheader }}
<ul role="tablist" class="nav nav-tabs">
{{# iconlist }}
{{# icons }}
{{> core/pix_icon }}
{{/ icons }}
{{/ iconlist }}
</ul>
{{/ tabheader }}
{{# tabbody }}
<div class="tab-content">
{{# tabcontent }}
{{# tabs }}
{{> core/notification_info}}
{{/ tabs }}
{{/ tabcontent }}
</div>
{{/ tabbody }}
</div>
{{#js}}
require(['jquery','core/tabs'], function($, tabs) {
var container = $("#{{ uniqid }}-tab-container");
tabs.create(container);
});
{{/js}}
TBD;
$templatewithcomment = <<<TBC
{{!
This file is part of Moodle - http://moodle.org/
Moodle is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Moodle is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Moodle. If not, see <http://www.gnu.org/licenses/>.
}}
{{!
@template mod_lemmings/lemmings
Lemmings template.
The purpose of this template is to render a lot of lemmings.
Classes required for JS:
* none
Data attributes required for JS:
* none
Context variables required for this template:
* attributes Array of name / value pairs.
Example context (json):
{
"lemmings": [
{ "name": "Lemmy Winks", "age" : 1, "size" : "big" },
{ "name": "Rocky", "age" : 2, "size" : "small" }
]
}
}}
$templatebody
{{!
Here's some more comment text
Note, there is no need to test bracketed variables inside comments as gherkin does not support that!
See this issue: https://github.com/mustache/spec/issues/8
}}
TBC;
// Ensure that the template when stripped of comments just includes the body.
$stripped = phpunit_util::call_internal_method(null, 'strip_template_comments',
[$templatewithcomment], 'core\output\external');
$this->assertEquals(trim($templatebody), trim($stripped));
$tokenizer = new Mustache_Tokenizer();
$tokens = $tokenizer->scan($templatebody);
$parser = new Mustache_Parser();
$tree = $parser->parse($tokens);
$this->assertNotEmpty($tree);
}
}

View file

@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
$version = 2018122000.00; // YYYYMMDD = weekly release date of this DEV branch.
$version = 2018122000.01; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.