Creating and modifying snippet context

Last updated on
12 April 2018

Terminology

Snippet context:
An array of named parameters to pass to the template (Twig variables).
Snippet variable:
Either snippet variable plugin instance or configuration for it.

Hooks

The simplest way to provide new snippet context or modify existing context is implementing hook_snippet_build_alter().

As you may have noticed this works quite similar to template preprocess hooks. It is also possible to alter existing context by implementing hook_snippet_context_alter().

/**
 * Implements hook_snippet_build_alter().
 */
function hook_snippet_build_alter(array &$build, SnippetInterface $snippet) {
  if ($snippet->id() == 'foo') {
    $build['snippet']['#context']['bar'] = 'Bar value';
  }
}

It is considered as a good practice to document such variables in a template.

{# @see from my_module_snippet_build_alter(). #}
<div>{{ bar }}</div>

Plugin

Implementing snippet variable plugin is a more generic way to supply your template with custom data. Snippet variables can be configured through the administrative interface so you will be able to reuse them for different content items. The example below shows how to create custom snippet variable type (formatted text).

<?php

namespace Drupal\module_name\Plugin\SnippetVariable;

use Drupal\Core\Form\FormStateInterface;
use Drupal\snippet_manager\SnippetVariableBase;
use Drupal\snippet_manager\SnippetVariableInterface;

/**
 * Provides text variable type.
 *
 * @SnippetVariable(
 *   id = "text",
 *   title = @Translation("Text"),
 *   category = @Translation("Other"),
 * )
 */
class Text extends SnippetVariableBase {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    $form['content'] = [
      '#title' => t('Content'),
      '#type' => 'text_format',
      '#default_value' => $this->configuration['content']['value'],
      '#format' => $this->configuration['content']['format'],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $configuration['content'] = [
      'value' => '',
      'format' => filter_default_format(),
    ];
    return $configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#type' => 'processed_text',
      '#text' => $this->configuration['content']['value'],
      '#format' => $this->configuration['content']['format'],
    ];
  }

}

More examples can be found under src/Plugin/SnippetVariable directory of the Snippet manager module.

Help improve this page

Page status: No known problems

You can: