In this tutorial, we will learn how to create and override paragraphs dynamically in Drupal 10 using Twig.
1. Create a Paragraph Type in Drupal 10
To create a new paragraph type in Drupal 10:
- Go to Structure > Paragraph types (
/admin/structure/paragraphs_type). - Click Add Paragraph Type and name it Custom Paragraph.
- Add the necessary fields (like text, title, image, etc.).
- Save the paragraph type.
2. Display Paragraph in a Twig Template
To customize how the paragraph is displayed in Drupal 10:
- Create a custom Twig file in your theme:
themes/custom/YOUR_THEME/templates/paragraph/ - Name the file paragraph--custom-paragraph.html.twig
Paste the following code inside the Twig file:
{% raw %}
{# Override paragraph template for "custom_paragraph" #}
{{ content.field_title }}
{{ content.field_text }}
{% endraw %}
3. Override a Paragraph Field
To customize how a field is displayed, modify the Twig template:
{% raw %}
{% if content.field_text %}
{{ content.field_text }}
{% endif %}
{% endraw %}
4. Apply CSS Styling
To style the paragraph, add CSS to your theme's CSS file:
.custom-paragraph {
border: 1px solid #ccc;
padding: 10px;
background: #f9f9f9;
}
5. Assign the Paragraph to a Content Type
- Go to Structure > Content Types.
- Edit the content type where you want to use paragraphs.
- Add a Paragraph Reference Field and choose Custom Paragraph.
- Save the content type and start adding content.
6. Clear Cache
After making changes, clear the Drupal cache:
drush cache:rebuild
Or go to Configuration > Performance > Clear Cache.
More Drupal Tutorials
Visit Developer Sahayak for more Drupal 10 tutorials.
0 Comments