drupal-vars-twig-js-notes.md 1.56 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Sending env vars from settings.php to twig and js

${toc}

## Goals

- Set up twig debugging
- Set up variables
  - Create environment variables in settings.local.php
  - Send to twig template
  - Send to theme .js

## Steps

1. enable twig debugging
   1. copy default.services.yml services.yml
   2. edit and enable debugging
1. local settings
   1. copy example.settings.local.php to default/settings.local.php
   2. add `exit;` to test
1. edit settings.php
   1. uncommenting settings.local.php include at bottom
   2. add env variable (below)
1. add [theme_preprocess_node()](https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/template_preprocess_node/9.3.x) to .theme file
1. edit node.twig
1. edit script.js

## Components

```
# enable debugging
$settings['env']['environment'] = 'local';
$settings['env']['url_services'] = 'http://local.example.com/';

# script.js
console.table(settings.env);

# node.twig
{% if env.environment=='local' %}
  this is local
{% endif %}

# ------------------------------------------
# theme preprocess function
# ------------------------------------------
 use Drupal\Core\Site\Settings;
 /**
 * Implements template_preprocess_node().
 */
function my_subtheme_preprocess_node(&$variables) {

  $node = $variables['node'];
  $node_type = $node->getType();

  if ($node_type === 'page') {
    // get from settings.local.php
    $env = Settings::get('env');

    // Send  to template.
    $variables['env'] = $env;

    // Send to js, via settings.env
    $variables['#attached']['drupalSettings']['env'] = $env;
  }

}

```