hokoo / templater

Lightweight, simple but powerful templater for rendering HTML templates in PHP
GNU General Public License v3.0
2 stars 0 forks source link

Gentle API for putting content into template #13

Open hokoo opened 2 weeks ago

hokoo commented 2 weeks ago

Suppose, we've got a template:

$template = <<<TEMPLATE
<div class="list">
  %s
  [[list-item]]
    %s

    [[logo]]
    <div class="logo">
      %s
    </div>
    [[/logo]]

    [[text]]<div class="text">%s</div>[[/text]]

    [[img]]<img src="%s" alt=""/>[[/img]]
  [[/list-item]]
</div>
TEMPLATE;

Sometimes it's getting hard to maintain such expressions as

$data = [
  [
    [
      'tag'     => 'list-item',
      'content' => [
        [
          [
            'tag'     => 'logo',
            'content' => [
              [
                [ 'tag' => 'img', 'content' => 'localhost//image1.jpg' ],
              ]
            ]
          ],
          [ 'tag' => 'text', 'content' => 'TEXT1' ],
        ]
      ],
    ],
  ],
];
hokoo commented 2 weeks ago

Obviously, more readable approach would be like this:

$img = TemplaterClient::getElement( tag: 'img' );
$img->append( 'localhost//image1.jpg' );

$logo = TemplaterClient::getElement( tag: 'logo' );
$logo->append( $img );

$text = TemplaterClient::getElement( tag: 'text' );
$text->append( 'TEXT1' );

$element = TemplaterClient::getElement();
$element->append( $logo );
$element->append( $text );

/*
 * The elements' number added into $list_item, equals the modifiers' number in the list-item tag.
 */
$list_item = TemplaterClient::getElement( 'list-item' );
$list_item->append( $element );

/**
 * The elements' number inside of $elements equals the top level modifiers number in the template.
 */
$elements = TemplaterClient::getElement();
$elements->append( $list_item );

$templater = new Templater();
$result = $templater->render( $template, $elements );