Template Studio
Info
The Template Studio’s Create variant operation creates a new
variant template based on the selected template.
Contao provides this operation for the Twig template prefix content_element/, frontend_module/ and page/. To offer
it for your own template groups, register an operation for their identifier prefix.
Adding a Create Variant Operation
Extend Contao\CoreBundle\Twig\Studio\Operation\AbstractCreateVariantOperation, add the
#[AsOperationForTemplateStudioElement] attribute and return your template identifier prefix in getPrefix().
For example, to support templates such as @Contao/foobar/latest.html.twig:
The operation must be registered as a service with autoconfiguration enabled. The Contao Managed Edition does this
automatically for classes in the App\ namespace under src/. In a bundle, use your bundle’s namespace and
register the service in its service configuration
and enable autoconfigure.
The operation name is derived from the class name: CreateFoobarVariantOperation becomes create_foobar_variant.
Provide its button label and tooltip in the contao_template_studio translation domain:
Selecting Create variant for foobar/latest.html.twig and entering highlight creates
templates/foobar/latest/highlight.html.twig. The generated template extends @Contao/foobar/latest.html.twig and can
then be edited in the Template Studio.
Matching Template Identifiers
By default, AbstractCreateVariantOperation::canExecute() offers the operation only outside a theme context and for
identifiers with exactly one segment below the prefix. With the prefix foobar, this includes foobar/latest, but
excludes foobar, foobar/_base and foobar/latest/highlight. Identifiers do not include the @Contao/ namespace or
file extension.
The prefix can contain multiple segments. For example, return foo/bar to support templates such as
@Contao/foo/bar/file.html.twig.
If you also want to support a template whose identifier equals the prefix itself, such as @Contao/foobar.html.twig,
import OperationContext and override canExecute() in your operation: