Zum Inhalt springen

Twig: Unterschied zwischen den Versionen

Aus Computech CMS Wiki
Simon Zeberli (Diskussion | Beiträge)
 
(51 dazwischenliegende Versionen von 4 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
=Twig Allgemein=
=Allgemein=
* [[Konventionen]]
* [[Konventionen]]
* [[Twig-Links]]
* [[Twig-Links]]
 
* [[Drupal 8 DEV Mode]]
==Twig Drupal8 Module==
==Twig Drupal8 Module==
* https://www.drupal.org/project/twig_tweak
* https://www.drupal.org/project/twig_tweak
==Twig Schnipsel==
[https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd Diverse Twig Schnipsel]
{| class="wikitable sortable"
|-
! Was!! Twig
|-
| Variable übersetzen || <syntaxhighlight lang="twig">{{ 'Read more'|trans }}</syntaxhighlight>
|-
| For Schleife || <syntaxhighlight line='line' lang="twig"> {% for val in array %}
    {{ val }}
{% endfor %}</syntaxhighlight>
|-
| Array enthält || <syntaxhighlight line='line' lang="twig">{% if "wert" in array %}</syntaxhighlight>
|-
| Array enthält nicht || <syntaxhighlight line='line' lang="twig">{% if "wert" not in array %}</syntaxhighlight><syntaxhighlight line='line' lang="twig">{% if content.field_slider_titel|render or content.field_slider_text|render is not empty %}</syntaxhighlight>
|-
| Odd & Even || <syntaxhighlight line='line' lang="twig">
    {% for row in rows %}
      {% set parity = cycle(['odd', 'even'], loop.index0) %}
      <tr {{ row.attributes.addClass(parity) }}>
</syntaxhighlight>
|}
==Field Value==
{| class="wikitable sortable"
|-
! Field Type !! Twig
|-
| image ||  <syntaxhighlight lang="twig">{{  }}</syntaxhighlight>
|-
| dropdown ||  <syntaxhighlight lang="twig">{{ content.field_slider_text_position['#items'].getString() }}</syntaxhighlight>
|-
| image URI||  <syntaxhighlight lang="twig">{{  paragraph.field_slider_bild.0.entity.uri.value }}</syntaxhighlight>
|}
=Templates=
=Templates=
==THEMENAME.theme Pre Process Funcitons==
===Modal===
===Value beim Feld ausgeben===
* Module mit Modal Form bauen: https://befused.com/drupal/modal-module
 
Node / Kontakt / Views / Webform in einem Modal öffnen: (mit Breitenanpassung)
<syntaxhighlight line='line' lang="html5">
<a class="use-ajax" data-dialog-options="{&quot;width&quot;:420,&quot;title&quot;:&quot;Kontakt Info&quot;}" data-dialog-type="modal" href="/contact">Contact US</a>
</syntaxhighlight>
hook_preprocess_page in die.theme-Datei einfügen um die modal-library anzuhängen:
<syntaxhighlight line='line' lang="php">
<syntaxhighlight line='line' lang="php">
function THEMENAME_preprocess_node(&$variables) {
function THEMENAME_preprocess_page(&$variables) {
     if ($variables['node']->getType() === 'NODEYPE') {
     //custom logic of when to include the library
        $variables['var_GESETZTE_VARIABLE'] = $variables['node']->field_FELDNAME->value;
    // ....
    }
    $variables['#attached']['library'][] = 'core/drupal.dialog.ajax';
}
}
</syntaxhighlight>
</syntaxhighlight>
Damit wird die Variable '''<nowiki>{{ var_GESETZTE_VARIABLE}}</nowiki>''' in jeder Twig datei aktiv.
====Modal mit URL Parametern====
 
URL-Parameter an Form übergeben:
==Sprach Umschalter==
in Datei '''THEMENAME.theme''' Folgenden Code einfügen:
<syntaxhighlight line='line' lang="php">
<syntaxhighlight line='line' lang="php">
function THEMENAME_preprocess_html(&$variables) {
function THEMENAME/MODULENAME_form_alter(&$form, $form_state, $form_id) {
     //sprachumschalter classe
  // target any form provided by the contact module. If you want to target a specific form use the form ID
     $variables['language'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
  if (strpos($form_id, 'contact_message_') !== FALSE) {
     // Set the default subject based off the subject query param.
     $default_subject = \Drupal::request()->query->get('subject');
    $form['subject']['widget'][0]['value']['#default_value'] = $default_subject;
   }
   }
}
</syntaxhighlight>
URL-Parameter mitgeben (Beispiel Anmeldung mit Subject 'Anmeldung: [Titel] [Datum]'):
<syntaxhighlight line='line' lang="twig">
{% set eventDateTimestamp = node.field_date.value|date('U') %}
{% set urlParams = {'subject': 'Anmeldung: ' ~ node.label ~ ' ' ~ eventDateTimestamp|date('j.n.Y') }|url_encode %}
<a class="use-ajax" data-dialog-type="modal" data-dialog-options="{&quot;width&quot;:400}" href="/contact?{{ urlParams }}">Anmelden</a>
</syntaxhighlight>
</syntaxhighlight>
Damit wird die Variable '''<nowiki>{{ language }}</nowiki>''' in jeder Twig datei aktiv.


===Datumfeld===
<syntaxhighlight line='line' lang="twig">
{% if content.field_datum_bis|render is not empty %}
  {{ content.field_datum.0["#attributes"].datetime|date('U')|format_date('datum_von') }} bis {{ content.field_datum_bis.0["#attributes"].datetime|date('U')|format_date('author') }}
{% else %}
  {{  content.field_datum.0["#attributes"].datetime|date("U")|format_date('author')  }}
  {# {{ dump(content.field_datum.0["#attributes"].datetime )}} #}
{% endif %}
</syntaxhighlight>
==Layout==
==Layout==
===html.html.twig===
===html.html.twig===
Zeile 34: Zeile 91:


==Block==
==Block==
===Template suggestion für custom-Blocktyp erzeugen===
<syntaxhighlight line='line' lang="php">
/**
* Implements hook_theme_suggestions_HOOK_alter() for form templates.
* @param array $suggestions
* @param array $variables
*/
function THEMENAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Block suggestions for custom block bundles.
  if (isset($variables['elements']['content']['#block_content'])) {
    array_splice($suggestions, 1, 0, 'block__bundle__' . $variables['elements']['content']['#block_content']->bundle());
  }
}
</syntaxhighlight>


==Content Node==
==Content Node==
Zeile 44: Zeile 115:
===Image Style Hardcodiert setzen===
===Image Style Hardcodiert setzen===
* einem Bild Feld - den Bildstil anpassen / Hardcodiert
* einem Bild Feld - den Bildstil anpassen / Hardcodiert
<syntaxhighlight line='line' lang="html5">
<syntaxhighlight line='line' lang="twig">
    {#{{ content.field_slider_bild }}#}
{#{{ content.field_slider_bild }}#}
    {% set image = content.field_slider_bild.0|merge({'#image_style': 'bild'}) %}
{% set image = content.field_slider_bild.0|merge({'#image_style': 'bild'}) %}
    {# {% set image = image|merge({'#image_style': 'bild'}) %}    Bildstil  #}
{# {% set image = image|merge({'#image_style': 'bild'}) %}    Bildstil  #}
    {{ image }}
{{ image }}
</syntaxhighlight>
</syntaxhighlight>
* Ein Bild, einem Bildstil einfügen -> kann für Paralax oder Hintergurnd verwendet werden.
* Ein Bild, einem Bildstil einfügen -> kann für Paralax oder Hintergurnd verwendet werden.
<syntaxhighlight line='line' lang="html5">
<syntaxhighlight line='line' lang="twig">
    {# Benötigtes Modul: https://www.drupal.org/project/twig_tweak #}
{# Benötigtes Modul: https://www.drupal.org/project/twig_tweak #}
    {# slider bild bildstile berechnen #}
{# slider bild bildstile berechnen #}
    {% set url_image_style = paragraph.field_slider_bild.0.entity.uri.value | image_style('slider_klein')  %}
{% set url_image_style = paragraph.field_slider_bild.0.entity.uri.value | image_style('slider_klein')  %}
    {# {{ url_image_style }} #}
{# {{ url_image_style }} #}
</syntaxhighlight>
 
===Vorhandene  "Image Style" auslesen===
<syntaxhighlight line='line' lang="twig">
$variables['var_image_styles'] = \Drupal::entityQuery('image_style')->execute();
</syntaxhighlight>
</syntaxhighlight>


Zeile 63: Zeile 139:
==THEMENAME.libraries.yml==
==THEMENAME.libraries.yml==
==THEMENAME.theme==
==THEMENAME.theme==
===Funktionen===
===preprocess function===
====THEMENAME_preprocess_html====
====Value beim Feld ausgeben====
<syntaxhighlight lang="php">
function genesis_preprocess_html(&$variables) {
    //sprachumschalter classe
    $variables['language'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
}
</syntaxhighlight>
 
====THEMENAME_preprocess_paragraph====
 
<syntaxhighlight line='line' lang="php">
<syntaxhighlight line='line' lang="php">
function THEMENAME_preprocess_paragraph(&$variables, $hook) {
function THEMENAME_preprocess_node(&$variables) {
    /* Attached Libraries for all Paragraphs */
     if ($variables['node']->getType() === 'NODEYPE') {
    $variables['#attached']['library'][] = 'smhl/paragraph-default';
         $variables['var_GESETZTE_VARIABLE'] = $variables['node']->field_FELDNAME->value;
   
    $paragraph = $variables['elements']['#paragraph'];
   
    /*
    * Class Attributes
    */
   
    /*
    * Paragraph §Text
    */
     if ($paragraph->bundle() == "p_text") {
        /* Field Position */
        $variables['var_field_position'] = $paragraph->get('field_position')->value;
        /* Field Breite */
        $field_breite = $paragraph->get('field_breite')->value;
        $variables['var_field_breite_eingabewert'] = $field_breite;
        $variables['var_field_breite_gegenwert'] = 12-$field_breite;
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
    }
   
    /*
    * Paragraph §Bild mit Text
    */
    if ($paragraph->bundle() == "p_bild_mit_text") {
        /* Field Position */
         $variables['var_field_position'] = $paragraph->get('field_position')->value;
        /* Field Breite */
        $field_breite = $paragraph->get('field_breite')->value;
        $variables['var_field_breite_eingabewert'] = $field_breite;
        $variables['var_field_breite_gegenwert'] = 12-$field_breite;
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
        /* Field Bildquelle */
        $variables['var_field_copyright'] = $paragraph->get('field_copyright')->value;
    }
   
    /*
    * Paragraph §Dateidownload
    */
    if ($paragraph->bundle() == "p_dateidownload") {
        /* Field Position */
        $variables['var_field_position'] = $paragraph->get('field_position')->value;
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
    }
   
    /*
    * Paragraph §Video mit Text
    */
    if ($paragraph->bundle() == "p_video_mit_text") {
        /* Field Position */
        $variables['var_field_position'] = $paragraph->get('field_position')->value;
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
     }
     }
    /*
    * Paragraph §Video mit Text
    */
    if ($paragraph->bundle() == "p_text_mit_block") {
        /* Field Position */
//        $variables['var_field_position'] = $paragraph->get('field_position')->value;
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
    }
    /*
    * Paragraph §Bildergalerie
    */
    if ($paragraph->bundle() == "p_bildergalerie") {
        $variables['var_field_bilder'] = $paragraph->get('field_bilder')->value;
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
        /* Field Bildquelle */
        $variables['var_field_copyright'] = $paragraph->get('field_copyright')->value;
    }
   
    /*
    * Paragraph §Titel
    */
    if ($paragraph->bundle() == "p_titel") {
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
        /* Field h_size */
        $variables['var_field_h_size'] = $paragraph->get('field_h_size')->value;
        /* Field Titel */
        $variables['var_field_titel'] = $paragraph->get('field_titel')->value;
    }
   
    /*
    * Paragraph §Video
    */
    if ($paragraph->bundle() == "p_video") {
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
    }
    /*
    * Paragraph §Video
    */
    if ($paragraph->bundle() == "p_audio") {
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
    }
   
    /*
    * Paragraph §Google Maps
    */
    if ($paragraph->bundle() == "p_google_maps") {
        /* Field Sprungmarke */
        $variables['var_field_sprungmarke'] = $paragraph->get('field_sprungmarke')->value;
    }
   
    /*
    * Paragraph §Bild
    */
    if ($paragraph->bundle() == "p_bild") {
        /* Field Breite */
        $variables['var_field_breite_eingabewert'] = $paragraph->get('field_breite')->value;
        /* Field Bildquelle */
        $variables['var_field_copyright'] = $paragraph->get('field_copyright')->value;
    }
   
    /*
    * Paragraph §Slider Blur
    */
    if ($paragraph->bundle() == "p_slider_blur") {       
        /* Field Bildquelle */
        // $variables['var_imgUrl'] = file_create_url($paragraph->get('field_slider_bild')->entity->uri->value);
        $variables['var_titel'] = $paragraph->get('field_slider_titel')->value;
    }
        /*
    * Paragraph §Slider Bild mit Text
    */
    if ($paragraph->bundle() == "p_slider_bildtext") {
        /* Field Bildquelle */
        $variables['var_imgUrl'] = file_create_url($paragraph->get('field_slider_bild')->entity->uri->value);
        $variables['var_titel'] = $paragraph->get('field_slider_titel')->value;
    } 
   
    /*
    * Paragraph §Box-Element
    */
    if ($paragraph->bundle() == "p_box_element") {
        $variables['var_imgUrl'] = file_create_url($paragraph->get('field_box_bild')->entity->uri->value);
        $variables['var_imgAlt'] = $paragraph->get('field_box_bild')->item->alt->value;
       
       
        /* Field Check-Icon */
        $check_icon = $paragraph->get('field_check_icon_anzeigen')->value;
        if ($check_icon == 1) {
            $variables['var_check_icon'] = "check-icon";
        } else {
            $variables['var_check_icon'] = "";
        }
    }
   
}
}
</syntaxhighlight>
</syntaxhighlight>
=====Referenz Field -> Node - Paragraph View Mode mitgeben =====
Damit wird die Variable '''<nowiki>{{ var_GESETZTE_VARIABLE}}</nowiki>''' in jeder Twig datei aktiv.
Ein Benutzer kann ein Paragraph erstellen indem er die Ansicht ändern kann.
 
* Einen Inhaltstyp erstellen
** Diesem Inhaltstyp sollten ein oder mehrere View Modes definiert werden
* Paragraph
** Ein Referenz Feld auf Content estellen "'''field_kontaktperson'''"
** Ein Listenfeld "'''field_inhaltsdarstellungen'''" (Dropdown) mit den Maschinenlesbaren Namen erstellen


====Sprach Umschalter====
in Datei '''THEMENAME.theme''' Folgenden Code einfügen:
<syntaxhighlight line='line' lang="php">
<syntaxhighlight line='line' lang="php">
if ($paragraph->bundle() == "p_side_kontakt_2") { //paragraphs Name
function THEMENAME_preprocess_html(&$variables) {
     if ($variables['paragraph']->hasField('field_inhaltsdarstellungen')) { //Dropdown Feld
    //sprachumschalter classe
        $view_mode = $variables['paragraph']->field_inhaltsdarstellungen->value;
     $variables['language'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
        if (isset($variables['content']['field_kontaktperson']['0']['#view_mode'])) {
  }
          $variables['content']['field_kontaktperson']['0']['#view_mode'] = $view_mode;
          unset($variables['content']['field_kontaktperson']['0']['#cache']['keys']);
        }
      }     
}
</syntaxhighlight>
 
=Drupal 8 DEV Mode=
==service.yml==
<syntaxhighlight line='line' lang="html4strict">
# ZeberliEDV Anpassungen - DEV umgebung
#Diesen Text oben in der Datei einfügen
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
#    debug: true
    auto_reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
   
</syntaxhighlight>
 
==settings.php==
<syntaxhighlight lang="php">
//DEV einstellungn - diese müssen beim Live Gelöscht werden!
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
 
 
/**
* DEBUGING - für die Entwicklung!
*/
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();
 
/**
* Enable local development services.
*/
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] =    'cache.backend.null';
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
$GLOBALS['_kint_settings']['maxLevels'] = 3;
</syntaxhighlight>
</syntaxhighlight>
Damit wird die Variable '''<nowiki>{{ language }}</nowiki>''' in jeder Twig datei aktiv.

Aktuelle Version vom 23. Juni 2021, 15:15 Uhr

Allgemein

Twig Drupal8 Module

Twig Schnipsel

Diverse Twig Schnipsel

Was Twig
Variable übersetzen
{{ 'Read more'|trans }}
For Schleife
 {% for val in array %}
    {{ val }}
{% endfor %}
Array enthält
{% if "wert" in array %}
Array enthält nicht
{% if "wert" not in array %}
{% if content.field_slider_titel|render or content.field_slider_text|render is not empty %}
Odd & Even
    {% for row in rows %}
      {% set parity = cycle(['odd', 'even'], loop.index0) %}
      <tr {{ row.attributes.addClass(parity) }}>

Field Value

Field Type Twig
image
{{  }}
dropdown
{{ content.field_slider_text_position['#items'].getString() }}
image URI
{{  paragraph.field_slider_bild.0.entity.uri.value }}

Templates

Node / Kontakt / Views / Webform in einem Modal öffnen: (mit Breitenanpassung)

<a class="use-ajax" data-dialog-options="{&quot;width&quot;:420,&quot;title&quot;:&quot;Kontakt Info&quot;}" data-dialog-type="modal" href="/contact">Contact US</a>

hook_preprocess_page in die.theme-Datei einfügen um die modal-library anzuhängen:

function THEMENAME_preprocess_page(&$variables) {
    //custom logic of when to include the library
    // ....
    $variables['#attached']['library'][] =  'core/drupal.dialog.ajax';
}

URL-Parameter an Form übergeben:

function THEMENAME/MODULENAME_form_alter(&$form, $form_state, $form_id) {
  // target any form provided by the contact module. If you want to target a specific form use the form ID
  if (strpos($form_id, 'contact_message_') !== FALSE) {
    // Set the default subject based off the subject query param.
    $default_subject = \Drupal::request()->query->get('subject');
    $form['subject']['widget'][0]['value']['#default_value'] = $default_subject;
  }
}

URL-Parameter mitgeben (Beispiel Anmeldung mit Subject 'Anmeldung: [Titel] [Datum]'):

{% set eventDateTimestamp = node.field_date.value|date('U') %}
{% set urlParams = {'subject': 'Anmeldung: ' ~ node.label ~ ' ' ~ eventDateTimestamp|date('j.n.Y') }|url_encode %}
<a class="use-ajax" data-dialog-type="modal" data-dialog-options="{&quot;width&quot;:400}" href="/contact?{{ urlParams }}">Anmelden</a>

Datumfeld

{% if content.field_datum_bis|render is not empty %}
   {{ content.field_datum.0["#attributes"].datetime|date('U')|format_date('datum_von') }} bis {{ content.field_datum_bis.0["#attributes"].datetime|date('U')|format_date('author') }}
{% else %}
   {{  content.field_datum.0["#attributes"].datetime|date("U")|format_date('author')  }}
   {# {{ dump(content.field_datum.0["#attributes"].datetime )}} #}
{% endif %}

Layout

html.html.twig

page.html.twig

maintenance-page.html.twig

region.html.twig

Block

Template suggestion für custom-Blocktyp erzeugen

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 * @param array $suggestions
 * @param array $variables
 */
function THEMENAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Block suggestions for custom block bundles.
  if (isset($variables['elements']['content']['#block_content'])) {
    array_splice($suggestions, 1, 0, 'block__bundle__' . $variables['elements']['content']['#block_content']->bundle());
  }
}

Content Node

Views

Field

Paragraph

Image Style Hardcodiert setzen

  • einem Bild Feld - den Bildstil anpassen / Hardcodiert
{#{{ content.field_slider_bild }}#}
{% set image = content.field_slider_bild.0|merge({'#image_style': 'bild'}) %}
{# {% set image = image|merge({'#image_style': 'bild'}) %}     Bildstil   #}
{{ image }}
  • Ein Bild, einem Bildstil einfügen -> kann für Paralax oder Hintergurnd verwendet werden.
{# Benötigtes Modul: https://www.drupal.org/project/twig_tweak #}
{# slider bild bildstile berechnen #}
{% set url_image_style = paragraph.field_slider_bild.0.entity.uri.value | image_style('slider_klein')  %}
{# {{ url_image_style }} #}

Vorhandene "Image Style" auslesen

$variables['var_image_styles'] = \Drupal::entityQuery('image_style')->execute();

Theme

THEMENAME.breakpoints.yml

THEMENAME.info.yml

THEMENAME.libraries.yml

THEMENAME.theme

preprocess function

Value beim Feld ausgeben

function THEMENAME_preprocess_node(&$variables) {
    if ($variables['node']->getType() === 'NODEYPE') {
        $variables['var_GESETZTE_VARIABLE'] = $variables['node']->field_FELDNAME->value;
    }
}

Damit wird die Variable {{ var_GESETZTE_VARIABLE}} in jeder Twig datei aktiv.

Sprach Umschalter

in Datei THEMENAME.theme Folgenden Code einfügen:

function THEMENAME_preprocess_html(&$variables) {
    //sprachumschalter classe
    $variables['language'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
  }

Damit wird die Variable {{ language }} in jeder Twig datei aktiv.