Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By kam3o on
Hello,
I want create custom template for each content type.
I have defined mytheme_theme_suggestions_page_alter(..) and files in /templates/*.html.twig. The problem is that drupal dont load content to template.
mytheme.theme
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$content_type = $node->bundle();
$suggestions[] = "page__".$content_type;
}
}
and files like:
page--mycontenttype.html.twig (node.html.twig from bartik theme)
...
{%
set classes = [
'node',
'node--type-' ~ node.bundle|clean_class,
node.isPromoted() ? 'node--promoted',
node.isSticky() ? 'node--sticky',
not node.isPublished() ? 'node--unpublished',
view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
'clearfix',
]
%}
{{ title_prefix }}
<!--{{ attach_library('classy/node') }}-->
<article{{ attributes.addClass(classes) }}>
<header>
{{ title_prefix }}
{% if not page %}
<h2{{ title_attributes.addClass('node__title') }}>
<a href="{{ url }}" rel="bookmark">{{ label }}</a>
</h2>
{% endif %}
{{ title_suffix }}
{% if display_submitted %}
<div class="node__meta">
{{ author_picture }}
<span{{ author_attributes }}>
{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
</span>
{{ metadata }}
</div>
{% endif %}
</header>
<div{{ content_attributes.addClass('node__content', 'clearfix') }}>
{{content}}
</div>
</article>
Result:
<article class="node node--type-mycontenttype node--promoted clearfix">
<header>
</header>
<div class="node__content clearfix">
</div>
</article>
Anyone have idea what i'm doing wrong?
Comments
When i change{{content}}
When i change
{{content}}
for
{{page.content}}
content is how but only content (at grey backgorund), without menu, footer etc.
When i change page--mycontenttype.html.twig for default bartik template the mycontenttype page displays properly but i need use node template becouse i need access to content.field_var. Any ideas?
=-=
I could be incorrect here but it seems to me you are trying to overwrite a page with a node template whereas you should be overriding a page with a page template. Thus you should be starting from page.html.twig rather than node.html.twig.
---
Your page template is where you set your header, footer, etc. The node template is where you play around with the content on the page.
{{ page.content }} -> is a page template variable
{{ content }} or {{ content.field_example }} -> are node template variables.
Node templates will be used within page templates. Rename your template to "node--mycontenttype.html.twig" and give that a try. As you mentioned in your original post you pulled the template code from the node.html.twig file and thus it should be within a node template file (not a page template).