mustache_templates-8.x-1.0-beta4/modules/mustache_magic/src/Plugin/mustache/Magic/Template.php
modules/mustache_magic/src/Plugin/mustache/Magic/Template.php
<?php
namespace Drupal\mustache_magic\Plugin\mustache\Magic;
use Drupal\mustache\Plugin\MustacheMagic;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Make contents reusable as a named template.
*
* Usage:
*
* You can use the "magical" {{#template.<name>}} variable to register
* enclosed contents as a named Mustache template. This can be then reused as
* partial or inclusion somewhere else.
*
* @code
* {{#template.greeting}}Hello {{name}}!{{/template.greeting}}
* {{#if.user.defined}}{{#user}}{{> greeting}}{{/user}}{{/if.user.defined}}
* @endcode
*
* @MustacheMagic(
* id = "template",
* label = @Translation("Template"),
* description = @Translation("Use <b>{{#template.<name>}}</b> to register enclosed contents as a named Mustache template. This can be then reused as partial or inclusion somewhere else. Examples: <ul><li>{{#template.greeting}}Hello {{name}}!{{/template.greeting}}<br/>{{#if.user.defined}}{{#user}}{{> greeting}}{{/user}}{{/if.user.defined}}</li></ul>")
* )
*/
class Template extends MustacheMagic {
/**
* Whether this object is a clone.
*
* @var bool
*/
protected $cloned = FALSE;
/**
* The template storage.
*
* @var \Drupal\mustache_magic\Storage\MustacheTemplateStorage
*/
protected $templateStorage;
/**
* The template name.
*
* @var string|null
*/
protected $templateName;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->templateStorage = $container->get('mustache.template_storage');
return $instance;
}
/**
* Implementation of the magic __isset() method.
*/
public function __isset($name): bool {
return !empty($name) || (!is_null($name) && is_scalar($name) && (trim((string) $name) !== ''));
}
/**
* Implementation of the magic __get() method.
*/
public function __get($name) {
if (!$this->cloned) {
$cloned = clone $this;
$cloned->cloned = TRUE;
return $cloned->__get($name);
}
$this->templateName = mb_strtolower(trim($name));
return $this;
}
/**
* Implements the magic __invoke() method, used as higher-order section.
*/
public function __invoke($template_content = NULL, $render = NULL) {
if (!isset($template_content, $render)) {
return;
}
$template_name = $this->templateName ?? hash('md4', $template_content);
$this->templateStorage->registerTemplate($template_name, $template_content);
return "";
}
}
