---
url: /cookbook/templating-tips.md
description: >-
  Use WPCE PHP helpers such as wpce_serialize_attrs(), wpce_serialize_style(),
  and get_element_html() when rendering templates.
---

# Common Templating Scenarios

## Serializing Attributes and Styles

The `wpce_serialize_attrs` function converts an array of attributes to a HTML attributes string. It offers some goodies over a naive `implode` implementation:

* A leading space is prepended (if any attributes are passed).
* Any HTML entities are escaped, so the string can be safely inserted into an HTML tag.
* Boolean attributes are allowed (`false`/`null` will omit the attribute, `true` will add it with no value).
* Non-associative array items are allowed (and are handled like boolean attributes with `true` value)
* `class`, `style` and `data` attributes may receive array values which are properly serialized.

### Examples

**Regular key-value pairs:**

```php
wpce_serialize_attrs([
	'href' => '#',
	'target' => '_blank'
]) === ' href="#" target="_blank"'
```

**Mixed associative and list items:**

```php
wpce_serialize_attrs([
	'type' => 'submit',
	'value' => 'Send now >>>',
	'disabled'
]) === ' type="button" value="Send now &gt;&gt;&gt;" disabled'
```

**Serialize attributes with boolean values:**

```php
wpce_serialize_attrs([
	'type' => 'text',
	'disabled' => false,
	'readonly' => true
]) === ' type="text" readonly'
```

**Showcase special handling for `class`, `style` and `data`:**

```php
wpce_serialize_attrs([
	'class' => ['foo', 'bar' => false, 'baz' => true],
	'style' => ['color' => 'red', 'background' => 'none'],
	'data' => ['x' => 'ok', 'y' => false, 'z' => true]
]) === ' class="foo baz" style="color: red; background: none" data-x="ok" data-z'
```

**Real world example:**

```php
add_filter('wpce_render_button', function ($wpce, $element) {
	$props = $element->properties;
	$label = htmlspecialchars($props->label);

	$attrs = [
		'href' => wpce_get_link($props->link),
		'target' => $props->link->target ? '_blank' : null,
		'class' => ['button', $props->link->target ? 'external' : null]
	];

	$attrs_string = wpce_serialize_attrs($attrs);

	return <<<HTML
		<a{$attrs_string}>{$label}</a>
		HTML;
});
```

:::tip
To only serialize the value of a `style` attribute, you can use the `wpce_serialize_style` function:

```php
wpce_serialize_style([ 'color' => 'red', 'background' => 'none' ])
=== 'color: red; background: none'
```

:::

## Rendering Child Elements

The `get_element_html` method can be used to render an element to an HTML string:

```php
add_filter('wpce_render_my-list-element', function ($wpce, $element) {
	$children_html = '';
	foreach ($element->children as $child) {
		$children_html .= '<li>' . $wpce->get_element_html($child) . '</li>';
	}

	return <<<HTML
		<ul>
			{$children_html}
		</ul>
		HTML;
}, 10, 2);
```

If child elements are not wrapped in something like a `<li>` tag, you may use the `get_inner_html` method as a terser, more expressive alternative:

```php
add_filter('wpce_render_my-container-element', function ($wpce, $element) {
	$children_html = $wpce->get_inner_html();

	return <<<HTML
		<div class="container">
			{$children_html}
		</div>
		HTML;
}, 10, 2);
```

## Render Programmatically Generated Elements

You can create an instance of a WPCE element on the fly by passing the element's identifier, props and children to the `create_element` method. Then use the `get_element_html` method to generate the HTML for that element.

The following example wraps all of its children in a `box` element:

```php
add_filter('wpce_render_boxwrapper', function ($wpce, $element) {
	$box = $wpce->create_element(
		'box',
		[ 'style' => 'style-default' ],
		$element->children
	);
	$box_html = $wpce->get_element_html($box);

	return $box_html;
}, 10, 2);
```

## Rendering Things Once Alongside an Element

Use the `is_first_occurrence` method to determine whether the currently rendered element is the first of its kind on the page. This can be used to include things that belong to an element but are not needed more than once per page, such as access tokens for third party services:

```php
add_filter('wpce_render_mapbox', function ($wpce) {
	$setup_html = '';
	if ($wpce->is_first_occurrence()) {
		$api_key = json_encode(get_mapbox_api_key());
		$setup_html = <<<HTML
			<script>window.mapbox_api_key = {$api_key};</script>'
			HTML;
	}
	
	return <<<HTML
		{$setup_html}
		<div class="map">...</div>
		HTML;
});
```
