Skip to content

Twig: Example Component

Salem Ghoweri edited this page Aug 8, 2018 · 22 revisions

Main Benefits

  1. Customizable HTML tag in the initially rendered markup
  2. Allowing the component's inner content to be overwritten via a Twig {% block block_name %}
  3. Consistent formatting

Code

Example 1: "Example" Component

{% set schema = bolt.data.components["@bolt-components-example"].schema %}

{% if enable_json_schema_validation %}
  {{ validate_data_schema(schema, _self) | raw }}
{% endif %}

{# Variables #}
{% set baseClass = "c-bolt-example" %}
{% set attributes = create_attribute(attributes|default({})) %}

{# Set up checks to validate that the component's prop values are allowed, based on the component's schema #}
{% set tagOptions = schema.properties.tag.enum %}
{% set propNameOptions = schema.properties.propName.enum %}
{% set sizeOptions = schema.properties.size.enum %}

{# Check that the component's current prop values are valid. if not, default to the schema default #}
{% set tag = tag in tagOptions ? tag : schema.properties.tag.default %}
{% set propName = propName in propNameOptions ? propName : schema.properties.propName.default %}
{% set size = size in sizeOptions ? size : schema.properties.size.default %}

{# Array of classes based on the defined + default props #}
{% set classes = [
  baseClass,
  size in sizeOptions ? "#{baseClass}--#{size}" : "",
] %}


{# Example component's custom element wrapper #}
<bolt-example
  {% if propName %} propName="{{ propName }}" {% endif %}
  {% if size %} size="{{ size }}" {% endif %}
>
  <{{ tag }} {{ attributes.addClass(classes) }}>
    {% block children %}
      {{ content }}
    {% endblock %}
  </{{ tag }}>
</bolt-example>

Example 2: "Simple" Component

Similar to the example above, only this time with deliberately more prescriptive initial HTML (for comparison).

{% set schema = bolt.data.components["@bolt-components-simple"].schema %}

{% if enable_json_schema_validation %}
  {{ validate_data_schema(schema, _self) | raw }}
{% endif %}

{# Variables #}
{% set baseClass = "c-bolt-simple" %}
{% set attributes = create_attribute(attributes|default({})) %}

{# set up checks to validate that the component's prop values are allowed, based on the component's schema #}
{% set layoutOptions = schema.properties.layout.enum %}

{# check that the component's current prop values are valid. if not, default to the schema default #}
{% set layout = layout in layoutOptions ? layout : schema.properties.layout.default %}

{# array of classes based on the defined + default props #}
{% set classes = [
  baseClass,
  layout in layoutOptions ? "#{baseClass}--#{layout}" : "",
] %}

{# example component's custom element wrapper #}
<bolt-simple
  {% if layout %} layout="{{ layout }}" {% endif %}
>
  <div {{ attributes.addClass(classes) }}>
    <div class="{{ baseClass }}__inner">
      {{ content }}
    </div>
  </div>
</bolt-simple>
Clone this wiki locally