Repository navigation
Document how to define mandatory/default props - #3132
Conversation
| Default values | ||
| ~~~~~~~~~~~~~~ | ||
|
|
||
| The ``{% props %}`` tag can also be used to define default values of an anonymous component. | ||
|
|
||
| .. code-block:: html+twig | ||
|
|
||
| {# templates/components/Image.html.twig #} | ||
| {% props size = 24 %} | ||
|
|
||
| <img src="/image.jpg" width="{{ size }}" height="{{ size }}" alt=""> | ||
|
|
||
| Then you can call the component with or without defining this value: | ||
|
|
||
| .. code-block:: html+twig | ||
|
|
||
| <twig:Image size="48"/> | ||
| <twig:Image/> | ||
|
|
||
| {# renders as: #} | ||
| <img src="/image.jpg" width="48" height="48" alt=""> | ||
| <img src="/image.jpg" width="24" height="24" alt=""> | ||
|
|
There was a problem hiding this comment.
I don't think we need a new section for default properties values, and the code examples seem wrong to me. What about changing the previous code block?
There was a problem hiding this comment.
What do you think is wrong in these examples?
The previous code blocks rely on {{ attributes.defaults({class: 'primary'}) }}: https://symfony.com/bundles/ux-twig-component/current/index.html#anonymous-components I preferred to separate these 2 different usages of props.
| .. code-block:: html+twig | ||
|
|
||
| {# templates/components/Button.html.twig #} | ||
| {% props icon = null, type = 'primary' %} | ||
|
|
||
| <button {{ attributes.defaults({class: 'btn btn-'~type}) }}> | ||
| {% block content %}{% endblock %} | ||
| {% if icon %} | ||
| <span class="fa-solid fa-{{ icon }}"></span> | ||
| {% endif %} | ||
| </button> |
There was a problem hiding this comment.
Instead, what about making icon prop required:
| .. code-block:: html+twig | |
| {# templates/components/Button.html.twig #} | |
| {% props icon, type = 'primary' %} | |
| <button {{ attributes.defaults({class: 'btn btn-'~type}) }}> | |
| {% block content %}{% endblock %} | |
| {% if icon %} | |
| <span class="fa-solid fa-{{ icon }}"></span> | |
| {% endif %} | |
| </button> |
and add some examples:
{# property "icon" is missing, an exception is thrown #}
<twig:Button>Share</twig:Button>
{# property "icon" is passed, property "type" use its default value "primary" #}
<twig:Button icon="share">Share</twig:Button>
{# both properties "icon" and "type" are passed #}
<twig:Button icon="share" type="secondary></twig:Button>There was a problem hiding this comment.
Thanks, I added it below the current examples because I think that showing props icon = null + {% if icon %} is interesting too.
435853b to
2420d50
Compare
2420d50 to
df4c94b
Compare
|
Thank you @alexisLefebvre. |
Here is a “trick” to define default values for anonymous components.