PHPackages                             nystudio107/craft-twigfield - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. nystudio107/craft-twigfield

Abandoned → [nystudio107/craft-code-editor](/?search=nystudio107%2Fcraft-code-editor)Yii2-extension[Templating &amp; Views](/categories/templating)

nystudio107/craft-twigfield
===========================

Provides a twig editor field with Twig &amp; Craft API autocomplete

1.0.18(3y ago)13112.5k↑25%41MITPHP

Since Jun 13Pushed 3y ago2 watchersCompare

[ Source](https://github.com/nystudio107/craft-twigfield)[ Packagist](https://packagist.org/packages/nystudio107/craft-twigfield)[ GitHub Sponsors](https://github.com/khalwat)[ RSS](/packages/nystudio107-craft-twigfield/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (22)Used By (1)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/0cbdf1e1ef97202d4000e0ee4e823fb28ad758562d0da77410bd0213a19488f4/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769676669656c642f6261646765732f7175616c6974792d73636f72652e706e673f623d7631)](https://scrutinizer-ci.com/g/nystudio107/craft-twigfield/?branch=develop) [![Code Coverage](https://camo.githubusercontent.com/3aa97d76aa585d48b322ed9f4687c75e76b04d469909e0fc57e8b9697024d91f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769676669656c642f6261646765732f636f7665726167652e706e673f623d7631)](https://scrutinizer-ci.com/g/nystudio107/craft-twigfield/?branch=develop) [![Build Status](https://camo.githubusercontent.com/46815063380fbbb97856940a199f7cf2525bfe4c3f550262264cf24604abbad8/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769676669656c642f6261646765732f6275696c642e706e673f623d7631)](https://scrutinizer-ci.com/g/nystudio107/craft-twigfield/build-status/develop) [![Code Intelligence Status](https://camo.githubusercontent.com/a16711dbb7329e989fe98df2ed3583b1cda17b7394d944631b0eacb45e20adf6/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769676669656c642f6261646765732f636f64652d696e74656c6c6967656e63652e7376673f623d7631)](https://scrutinizer-ci.com/code-intelligence)

DEPRECATED
==========

[](#deprecated)

Twigfield is now deprecated; please use [nystudio107/craft-code-editor](https://github.com/nystudio107/craft-code-editor) instead, which is a general purpose code editor that also does Twig &amp; autocompletes.

Twigfield for Craft CMS 3.x &amp; 4.x
=====================================

[](#twigfield-for-craft-cms-3x--4x)

Provides a twig editor field with Twig &amp; Craft API autocomplete

[![Demo](./resources/twigfield-demo.gif)](./resources/twigfield-demo.gif)

Requirements
------------

[](#requirements)

Twigfield requires Craft CMS 3.0 or 4.0.

Installation
------------

[](#installation)

To install Twigfield, follow these steps:

1. Open your terminal and go to your Craft project:

    ```
     cd /path/to/project

    ```
2. Then tell Composer to require the package:

    ```
     composer require nystudio107/craft-twigfield

    ```

About Twigfield
---------------

[](#about-twigfield)

Twigfield provides a full-featured Twig editor with syntax highlighting via the powerful [Monaco Editor](https://microsoft.github.io/monaco-editor/) (the same editor that is the basis for VS Code).

Twigfield provides full autocompletion for [Twig](https://twig.symfony.com/doc/3.x/) filters/functions/tags, and the full [Craft CMS](https://craftcms.com/docs/4.x/) API, including installed plugins:

[![Autocomplete](./resources/twigfield-autocomplete.png)](./resources/twigfield-autocomplete.png)

And it adds hover documentation when you hover the cursor over an expression:

[![Hovers](./resources/twigfield-hovers.png)](./resources/twigfield-hovers.png)

You can also add your own custom Autocompletes, and customize the behavior of the editor.

Twigfield also provides a [Yii2 Validator](https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators) for Twig templates and object templates.

Using Twigfield
---------------

[](#using-twigfield)

Once you've added the `nystudio107/craft-twigfield` package to your plugin, module, or project, no further setup is needed. This is because it operates as an auto-bootstrapping Yii2 Module.

Twigfield is not a Craft CMS plugin, rather a package to be utilized by a plugin, module, or project.

It can be very easy to add to an existing project, as you can see from the [Preparse field pull request](https://github.com/besteadfast/craft-preparse-field/pull/81/files) that adds it the [Preparse plugin](https://github.com/besteadfast/craft-preparse-field).

### In the Craft CP

[](#in-the-craft-cp)

Twigfield works just like the Craft CMS `forms` macros that should be familiar to plugin and module developers.

#### Import Macros

[](#import-macros)

Simply import the macros:

```
{% import "twigfield/twigfield" as twigfield %}
```

#### Multi-line Editor

[](#multi-line-editor)

Then to create a `textarea` multi-line editor, do the following:

```
{{ twigfield.textarea({
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: textAreaText,
}) }}
```

...where `textAreaText` is a variable containing the initial text that should be in the editor field. This will create the Twig editor.

To create a `textareaField` multi-line editor, do the following:

```
{{ twigfield.textareaField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: textAreaText,
}) }}
```

...where `textAreaText` is a variable containing the initial text that should be in the editor field. This will create the `label` and `instructions`, along with the Twig editor.

#### Single-line Editor

[](#single-line-editor)

Then to create a `text` single-line editor, do the following:

```
{{ twigfield.text({
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: text,
}) }}
```

...where `text` is a variable containing the initial text that should be in the editor field. This will create the Twig editor that is restricted to a single line, for simple Twig expressions.

To create a `textField` single-line editor, do the following:

```
{{ twigfield.textField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: text,
}) }}
```

...where `text` is a variable containing the initial text that should be in the editor field. This will create the `label` and `instructions`, along with the Twig editor that is restricted to a single line, for simple Twig expressions.

Regardless of the macro used, an Asset Bundle containing the necessary CSS &amp; JavaScript for the editor to function will be included, and the editor initialized.

### In Frontend Templates

[](#in-frontend-templates)

By default, Twigfield will not work in frontend templates, unless you specifically enable it.

Do so by copying the `config.php` file to the Craft CMS `config/` directory, renaming the file to `twigfield.php` in the process, then set the `allowFrontendAccess` setting to `true`:

```
return [
    // Whether to allow anonymous access be allowed to the twigfield/autocomplete/index endpoint
    'allowFrontendAccess' => true,
    // The default autcompletes to use for the default `Twigfield` field type
    'defaultTwigfieldAutocompletes' => [
        CraftApiAutocomplete::class,
        TwigLanguageAutocomplete::class,
    ]
];
```

Then import the macros:

```
{% import "twigfield/twigfield" as twigfield %}
```

Create your own `` element and include the necessary JavaScript, passing in the `id` of your `textarea` element:

```

{{ twigfield.includeJs("myTwigfield") }}
```

Enabling the `allowFrontendAccess` setting allows access to the `twigfield/autocomplete/index` endpoint, and add the `twigfield/templates` directory to the template roots.

### Additional Options

[](#additional-options)

The `textarea`, `textareaField`, `text`, `textField`, and `includeJs` macros all take four additional optional parameters:

```
{{ textarea(config, fieldType, wrapperClass, editorOptions, twigfieldOptions) }}

{{ textareaField(config, fieldType, wrapperClass, editorOptions, twigfieldOptions }}

{{ text(config, fieldType, wrapperClass, editorOptions, twigfieldOptions) }}

{{ textField(config, fieldType, wrapperClass, editorOptions, twigfieldOptions }}

{{ includeJs(fieldId, fieldType, wrapperClass, editorOptions, twigfieldOptions }}
```

#### `fieldType`

[](#fieldtype)

**`fieldType`** - an optional 2nd parameter. By default this is set to `Twigfield`. You only need to change it to something else if you're using a custom Autocomplete (see below)

e.g.:

```
{{ twigfield.textarea({
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: textAreaText,
}), "MyCustomFieldType" }}
```

#### `wrapperClass`

[](#wrapperclass)

**`wrapperClass`** - an optional 3rd parameter. An additional class that is added to the Twigfield editor wrapper `div`. By default, this is an empty string.

e.g.:

```
{{ twigfield.textareaField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: textAreaText,
}), "Twigfield", "monaco-editor-background-frame" }}
```

The `monaco-editor-background-frame` class is bundled, and will cause the field to look like a Craft CMS editor field, but you can use your own class as well.

There also a `monaco-editor-inline-frame` bundled style for an inline editor in a table cell (or elsewhere that no chrome is desired).

Both of these bundled styles use an accessibility focus ring when the editor is active, which mirrors the Craft CP style.

#### `editorOptions`

[](#editoroptions)

**`editorOptions`** - an optional 4th parameter. This is an [EditorOption](https://microsoft.github.io/monaco-editor/api/enums/monaco.editor.EditorOption.html) passed in to configure the Monaco editor. By default, this is an empty object.

e.g.:

```

{{ twigfield.includeJs("myTwigfield", "Twigfield", "monaco-editor-background-frame", {
    lineNumbers: 'on',
}) }}
```

#### `twigfieldOptions`

[](#twigfieldoptions)

**`twigfieldOptions`** - an optional 5th parameter. This object that can contain any data you want to pass from your Twig template down to the Autocomplete. This can be leveraged in custom Autocompletes to pass contextual for a particular field to the Autocomplete (see below)

e.g.:

```
{{ twigfield.textareaField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: 'myTwigfield',
    name: 'myTwigfield',
    value: textAreaText,
}), "Twigfield", "monaco-editor-background-frame", { lineNumbers: 'on' }, {
   'key': value,
   'key2': value2,
} }}
```

Using Additional Autocompletes
------------------------------

[](#using-additional-autocompletes)

By default, Twigfield uses the `CraftApiAutocomplete` &amp; `TwigLanguageAutocomplete`, but it also includes an optional `EnvironmentVariableAutocomplete` which provides autocompletion of any Craft CMS [Environment Variables](https://craftcms.com/docs/4.x/config/#environmental-configuration) and [Aliases](https://craftcms.com/docs/4.x/config/#aliases).

If you want to use the `EnvironmentVariableAutocomplete` or a custom Autocomplete you write, you'll need to add a little PHP code to your plugin, module, or project:

```
use nystudio107\twigfield\autocompletes\EnvironmentVariableAutocomplete;
use nystudio107\twigfield\events\RegisterTwigfieldAutocompletesEvent;
use nystudio107\twigfield\services\AutocompleteService;

Event::on(
    AutocompleteService::class,
    AutocompleteService::EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES,
    function (RegisterTwigfieldAutocompletesEvent $event) {
        $event->types[] = EnvironmentVariableAutocomplete::class;
    }
);
```

The above code will add Environment Variable &amp; Alias autocompletes to all of your Twigfield editors.

However, because you might have several instances of a Twigfield on the same page, and they each may provide separate Autocompletes, you may want to selectively add a custom Autocomplete only when the `fieldType` matches a specific.

Here's an example from the [Sprig plugin](https://github.com/putyourlightson/craft-sprig):

```
use nystudio107\twigfield\events\RegisterTwigfieldAutocompletesEvent;
use nystudio107\twigfield\services\AutocompleteService;
use putyourlightson\sprig\plugin\autocompletes\SprigApiAutocomplete;

public const SPRIG_TWIG_FIELD_TYPE = 'SprigField';

Event::on(
    AutocompleteService::class,
    AutocompleteService::EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES,
    function (RegisterTwigfieldAutocompletesEvent $event) {
        if ($event->fieldType === self::SPRIG_TWIG_FIELD_TYPE) {
            $event->types[] = SprigApiAutocomplete::class;
        }
    }
);
```

This ensures that the `SprigApiAutocomplete` Autocomplete will only be added when the `fieldType` passed into the Twigfield macros is set to `SprigField`.

Additionally, you may have an Autocomplete that you want to pass config information down to when it is instantiated. You can accomplish that by adding the Autocomplete as an array:

```
use nystudio107\twigfield\autocompletes\CraftApiAutocomplete;
use nystudio107\twigfield\events\RegisterTwigfieldAutocompletesEvent;
use nystudio107\twigfield\services\AutocompleteService;

Event::on(
    AutocompleteService::class,
    AutocompleteService::EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES,
    function (RegisterTwigfieldAutocompletesEvent $event) {
         $config = [
             'additionalGlobals' => $arrayOfVariables,
         ];
        $event->types[] = [CraftApiAutocomplete::class => $config];
    }
);
```

Note that all of the above examples *add* Autocompletes to the Autocompletes that Twigfield provides by default (`CraftApiAutocomplete` and `TwigLanguageAutocomplete`). If you want to *replace* them entirely, just empty the `types[]` array first:

```
        $event->types[] = [];
        $event->types[] = [CraftApiAutocomplete::class => $config];
```

Writing a Custom Autocomplete
-----------------------------

[](#writing-a-custom-autocomplete)

Autocompletes extend from the base [Autocomplete](https://github.com/nystudio107/craft-twigfield/blob/develop/src/base/Autocomplete.php) class, and implement the [AutocompleteInterface](https://github.com/nystudio107/craft-twigfield/blob/develop/src/base/AutocompleteInterface.php)

A simple Autocomplete would look like this:

```
