mustache_templates-8.x-1.0-beta4/src/Element/MustacheTemplateJsInline.php
src/Element/MustacheTemplateJsInline.php
<?php
namespace Drupal\mustache\Element;
use Drupal\Core\Render\Element\RenderElement;
/**
* Provides an element for adding Mustache templates as inline Javascript.
*
* @RenderElement("mustache_template_js_inline")
*/
class MustacheTemplateJsInline extends RenderElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
$class = get_class($this);
return [
'#theme' => 'mustache_template_js_inline',
'#pre_render' => [
[$class, 'generateTemplateContent'],
],
];
}
/**
* Generates the content of the Mustache template inline.
*
* @param array $element
* The element to render.
*
* @return array
* The element to render.
*/
public static function generateTemplateContent(array $element) {
/** @var \Drupal\mustache\MustacheTemplates $templates */
$templates = \Drupal::service('mustache.templates');
$template_name = $element['#template'];
if (isset($element['#inline']) && $element['#inline'] !== FALSE) {
$template_content = $element['#inline'];
}
else {
$template_content = $templates->getContent($template_name);
}
$template_encoded = trim(substr(json_encode($template_content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT), 1, -1));
$element['#template'] = [
'name' => $template_name,
'content' => $template_content,
'encoded' => $template_encoded,
];
$element['#attached']['library'][] = 'mustache/sync.now';
return $element;
}
}
