linkorb/custom-element

v1.0.0 2021-11-14 13:56 UTC

This package is auto-updated.

Last update: 2021-11-14 13:57:25 UTC


README

This library allows you to define custom elements for usage in (Twig) templates.

Think of it as light-weight SSR (Server Side Rendererd) Web Components.

For example, you can create a new element such as <Avatar username="alice" imageUrl="https://example.web/alice.webp" bio="Hello world" />

Then you define a twig template elements/Avatar.html.twig such as the following:

<div class="card avatar">
  <div class="card-body">
    <h1>{{username}}</h1>
    {% if imageUrl is defined %}
      <img src="{{ imageUrl }}" class="avatar-image" />
    {% endif %}
    {% if bio is defined %}
      <small>{{ bio }}</small>
    {% endif %}
  </div>
</div>

Your custom element can now be rendered using your custom element template. The template receives a variable for every specified attribute.

Custom elements will only be rendered if they start with an upper-case character (to distinguish standard from custom elements)

Usage

Symfony

Add the following to your services.yaml to register the renderer and the twig extension:

services:
    LinkORB\Component\CustomElement\Twig\CustomElementExtension:
        tags: ['twig.extension']
    LinkORB\Component\CustomElement\CustomElementRenderer: ~

The renderer

You can turn any raw HTML with custom elements into a rendered HTML output like this:

$renderer = new Renderer($twig);
$html = $renderer->render($htmlWithCustomElements);

The Twig extension

You can render custom elements from any Twig template using the filter:

<h1>Example</h1
{{ html|custom_element_render|raw }}

License

MIT. Please refer to the license file for details.

Brought to you by the LinkORB Engineering team

687474703a2f2f7777772e6c696e6b6f72622e636f6d2f642f6d6574612f74696572312f696d616765732f6c696e6b6f7262656e67696e656572696e672d6c6f676f2e706e67
Check out our other projects at linkorb.com/engineering.

Btw, we're hiring!