Server rendered components with template fragments and webcomponents
As I use webcomponents more, I found myself wanting a way to define the HTML for webcomponents with a non-trivial amount of light DOM contents in a more reusable programatic way. So far, I’ve found that modelling webcomponents as template fragments is a reasonably ergonomic solution. It enables usage such as:
- echo $this->element('components/select_box', ['options' => $options, 'name' => 'project_id');
This approach lets us model webcomponents with an interface that feels close to server rendered components. We can easily pass our ORM entities, API responses and calculated data into self-contained ‘functional components’ that generate the necessary HTML for a webcomponent. For example our select_box
template component could have the following contents:
- <?php
- $hidden = $this->templates->format('input', [
- 'name' => $data['name'],
- 'value' => $selected,
- 'type' => 'text',
- 'attrs' => $this->templates->formatAttributes($inputAttrs),
- ]);
- $optionsSet = [];
- foreach ($options as $option) {
- '<select-box-option value="%s">%s</select-box-option>',
- $option['value'] ?? null,
- $option['name']
- );
- }
- ?>
- <select-box name="{{name}}"{{attrs}}>
- <?= $hidden ?>
- <select-box-current>
- <span class="select-box-value"></span>
- <input type="text" class="select-box-input" />
- </select-box-current>
- </select-box>
Without any additional styling our custom HTML element will render as a div. However, we can use the custom componentn name in our CSS as well. This gives us a great way to attach our application’s CSS to named parts of the DOM. For more interactive components, you can also define a webcomponent class in JavaScript.
It’s that easy
There isn’t much to this pattern beyond that. We pair functional blocks of our application’s HTML and behavior to template fragments and webcomponents for any client-side interactions. With this solution we have a simple convention for pairing server rendered HTML and our client-side components. I’m going to continue exploring this pattern, but so far this ia a powerful and scalable way to design server rendered applications.
There are no comments, be the first!