Yes, it’s possible to preview Drupal content by content type in Twig templates. Here’s a refined version of the theme suggestion alter function that addresses the potential issues and incorporates best practices:
PHP
function your_theme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
// Ensure the node preview is available
if (isset($variables['node_preview']) && $variables['node_preview'] instanceof NodeInterface) {
$node_preview = $variables['node_preview'];
// Add content type-specific suggestions
$suggestions[] = 'page__node__preview__' . $node_preview->bundle();
// Add view mode-specific suggestions (if applicable)
if (isset($variables['view_mode']) && $variables['view_mode']) {
$suggestions[] = 'page__node__preview__' . $node_preview->bundle() . '__' . $variables['view_mode'];
}
}
}
Explanation:
Check for Node Preview: The function first verifies if the node_preview variable is set and contains a NodeInterface object. This ensures that we’re dealing with a node preview context.
Add Content Type Suggestion: If the node preview is available, the page__node__preview__' . $node_preview->bundle() suggestion is added. This will look for a template file named page--node--preview--CONTENT-TYPE.html.twig , where CONTENT-TYPE is replaced with the actual content type (e.g., page--node--preview--article.html.twig ).
Add View Mode Suggestion: If a view mode is specified (e.g., full , teaser ), the page__node__preview__' . $node_preview->bundle() . '__' . $variables['view_mode'] suggestion is added. This allows for further customization based on the view mode (e.g., page--node--preview--article--teaser.html.twig ).
Usage:
Create Template Files: Create template files following the naming conventions described above (e.g., page--node--preview--article.html.twig , page--node--preview--article--teaser.html.twig ).
Clear Cache: After creating or modifying the template files, clear the Drupal cache to ensure the new suggestions are recognized.
Additional Tips:
Consider using a theme’s theme_suggestions function to define additional suggestions based on your specific theme’s structure.
If you need to access the node entity within your template, you can use the node_preview variable.
You can customize the content of the preview templates to match your specific requirements.
By following these steps, you should be able to effectively preview Drupal content by content type and create tailored templates for different content types and view modes.