Захват атрибутов для ветки из контроллера

Я использую Drupal и имею ветку для шаблона html. Я новичок в этом проекте и вижу, что у него есть контроллер с функцией, которая запрашивает базу данных, а затем они возвращают этот запрос для атрибутов страницы курса, и я вижу, где атрибуты отображаются в соответствующем course.twig.html.

Я не вижу, как они связаны и откуда twig.html знает, откуда берутся его атрибуты. Я пытаюсь добавить на страницу еще несколько атрибутов и не вижу, как этот проект передает запросы mysql в шаблон веточки.

{#
/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - node: Full node entity.
 *   - id: The node ID.
 *   - bundle: The type of the node, for example, "page" or "article".
 *   - authorid: The user ID of the node author.
 *   - createdtime: Time the node was published formatted in Unix timestamp.
 *   - changedtime: Time the node was changed formatted in Unix timestamp.
 * - label: The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - author_picture: The node author user entity, rendered using the "compact"
 *   view mode.
 * - metadata: Metadata for this node.
 * - date: Themed creation date field.
 * - author_name: Themed author name field.
 * - url: Direct URL of the current node.
 * - display_submitted: Whether submission information should be displayed.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class element may contain one or more of the following
 *   classes:
 *   - node: The current template type (also known as a "theming hook").
 *   - node--type-[type]: The current node type. For example, if the node is an
 *     "Article" it would result in "node--type-article". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - node--view-mode-[view_mode]: The View Mode of the node; for example, a
 *     teaser would result in: "node--view-mode-teaser", and
 *     full: "node--view-mode-full".
 *   The following are controlled through the node publishing options.
 *   - node--promoted: Appears on nodes promoted to the front page.
 *   - node--sticky: Appears on nodes ordered above other non-sticky nodes in
 *     teaser listings.
 *   - node--unpublished: Appears on unpublished nodes visible only to site
 *     admins.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - content_attributes: Same as attributes, except applied to the main
 *   content tag that appears in the template.
 * - author_attributes: Same as attributes, except applied to the author of
 *   the node tag that appears in the template.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - view_mode: View mode; for example, "teaser" or "full".
 * - teaser: Flag for the teaser state. Will be true if view_mode is 'teaser'.
 * - page: Flag for the full page state. Will be true if view_mode is 'full'.
 * - readmore: Flag for more state. Will be true if the teaser content of the
 *   node cannot hold the main body content.
 * - logged_in: Flag for authenticated user status. Will be true when the
 *   current user is a logged-in member.
 * - is_admin: Flag for admin user status. Will be true when the current user
 *   is an administrator.
 *
 * @see template_preprocess_node()
 *
 * @todo Remove the id attribute (or make it a class), because if that gets
 *   rendered twice on a page this is invalid CSS for example: two lists
 *   in different view modes.
 *
 * @ingroup themeable
 */
#}

{# {{ kint() }} #}

<article id = "node-{{ node.id }}" {{ attributes }}>
{{node}}
  {{ title_prefix }}
  {% if not page %}
    <h2{{ title_attributes }}>
      <a href = "{{ url }}" rel = "bookmark">{{ label }}</a>
    </h2>
  {% endif %}
  {{ title_suffix }}

  {% if node.field_packaging.value == '1' %}

    {% set image = content.field_image %}
    {% set ce = content.field_tax_credit_hours %}
    {% set goal = content.field_goal %}
    {% set target_audience = content.field_audience %}
    {% set objectives = content.field_objectives %}
    {% set accreditation = content.field_accreditation %}
    {% set disclosure = content.field_disclosure_statement %}
    {# {% set references_old = content.field_references %} #}
    {% set references = content.field_references_par %}
    {% set appendix = content.field_appendix %}
    {% set faculty = content.field_faculty %}
    {% set related_courses = content.field_related_courses %}
    {# set suggested_courses = content.field_suggested_courses #}
    {% set additional = content.field_callout %}
    {% set expiration = node.field_expiration.value %}

    <div class = "course-summary row">
      {% if image|render %}
        <div class = "course-image small-6 small-offset-3 medium-4 medium-offset-0 columns">
            {{ image }}
        </div>
        <div class = "small-12 medium-8 columns">
      {% else %}
        <div class = "small-12 columns">
      {% endif %}
        <div class = "course-introduction">
          <p>Welcome to <em>{{ label }}</em>.</p>
        </div>
        {% if not resource  %}
          {% if ce.0|render %}
            <small class = "credit-hours inline-label">Credit hours: {{ ce.0 }} CE</small>
          {% endif %}
        {% endif %}
        <div class = "enroll">
          {% if signIn == "yes"  %}
           {% if regis == true %}
              <a href = "appLms/index.php?modname=course&op=aula&idCourse = {{ content.field_docebo_course_id.0 }}" class = "button large">Go</a>
           {% else %}
              <a href = "#" id = "regis" rel = "{{ content.field_docebo_course_id.0 }}" class = "button large">Enroll</a>
           {% endif %}
          {% else %}
            <a href = "dashboard/login?lms_id = {{ signURL }}" class = "button large">Enroll</a>
          {% endif %}
        </div>
      </div>
    </div>

    {% if goal|render or objectives|render %}

      <ul class = "tabs some-tabs" data-responsive-accordion-tabs = "tabs small-accordion medium-tabs" data-allow-all-closed = "true" data-multi-expand = "true" id = "course-tabs">
        <li class = "tabs-title is-active"><a href = "#overview" aria-selected = "true">Overview</a></li>

        {% if appendix|render %}
          <li class = "tabs-title"><a href = "#appendix">Appendix</a></li>
        {% endif %}

        {% if references|render %}
          <li class = "tabs-title"><a href = "#references">References</a></li>
        {% endif %}

        {% if faculty|render %}
          <li class = "tabs-title"><a href = "#faculty">Faculty</a></li>
        {% endif %}
      </ul>

      <div class = "tabs-content" data-tabs-content = "course-tabs">

        <div id = "overview" class = "tabs-panel is-active course-overview">

          {{ additional|render ? additional }}

          {% if goal|render %}
            <h2 class = "field-label">{{ node.field_goal.fielddefinition.label }}</h2>

            {{ goal }}
          {% endif %}

          <h2 class = "field-label">{{ node.field_audience.fielddefinition.label }}</h2>

          {% if target_audience|render %}
            {{ target_audience }}
          {% else %}
            <p>interested health-care professionals.</p>
          {% endif %}

          {% if objectives|render %}
            <h2 class = "field-label">{{ node.field_objectives.fielddefinition.label }}</h2>
            <p>After completing the activities of this module, you will be able to:</p>
            {{ objectives }}
          {% endif %}

          {% if expiration|render %}
            <p>Please note this module expires on <strong>{{ expiration|date('n/j/Y') }}</strong>.</p>
          {% endif %}

          {% if accreditation|render or disclosure|render %}

            <div class = "course-supplements">

              {% if accreditation|render %}

                <h2 class = "supplement-title"><a href = "#accreditation" class = "callout-link" data-toggle = "accreditation">Accreditation Statement</a></h2>

                <div id = "accreditation" class = "callout callout-arrow is-hidden" data-toggler = ".is-hidden">

                  {% for i, value in accreditation %}
                    {% set acc_item = node.field_accreditation[i].entity %}
                    {% if acc_item %}
                      <h3>{{ acc_item.title.value }}</h3>
                      {% autoescape false %}
                        {{ acc_item.body.value|replace({'{{ #.## }}': ce.0|escape }) }}
                      {% endautoescape %}
                    {% endif %}
                  {% endfor %}

                  <button class = "close-button" data-toggle = "accreditation">&times;</button>
                </div>

              {% endif %}

              {% if disclosure|render %}

                <h2 class = "supplement-title"><a href = "#disclosure" class = "callout-link" data-toggle = "disclosure">Disclosures</a></h2>

                <div id = "disclosure" class = "callout callout-arrow is-hidden" data-toggler = ".is-hidden">
                  {{ disclosure }}
                  <button class = "close-button" data-toggle = "disclosure">&times;</button>
                </div>

              {% endif %}

            </div>

          {% endif %}

        </div>

        {% if appendix|render %}

          <div id = "appendix" class = "tabs-panel course-appendix">

            {% if appendix %}

              <ul class = "tabs tabs-style-text" data-tabs id = "course-appendix-tabs">
                {% for i, value in node.field_appendix.value %}
                  {% set ref_title = node.field_appendix[i].entity.field_title.value %}
                  {% if ref_title %}
                    <li class = "tabs-title{{ i == 0 ? ' is-active'}}"><a href = "#{{ ref_title|clean_class }}" aria-selected = "{{ i == 1 ? 'true' : 'false' }}">{{ ref_title }}</a></li>
                  {% endif %}
                {% endfor %}
              </ul>

              <div class = "tabs-content" data-tabs-content = "course-appendix-tabs">
                {% for i, value in node.field_appendix.value %}
                  <div id = "{{ node.field_appendix[i].entity.field_title.value|clean_class }}" class = "tabs-panel{{ i == 0 ? ' is-active'}}">
                    {% autoescape false %}
                      {{ node.field_appendix[i].entity.field_content.value }}
                    {% endautoescape %}
                  </div>
                {% endfor %}
              </div>

            {% endif %}

          </div>

        {% endif %}

        {% if references|render %}

          <div id = "references" class = "tabs-panel course-references">

            {% if references %}

              <ul class = "tabs tabs-style-text" data-tabs id = "course-references-tabs">
                {% for i, value in node.field_references_par.value %}
                  {% set ref_title = node.field_references_par[i].entity.field_title.value %}
                  {% if ref_title %}
                    <li class = "tabs-title{{ i == 0 ? ' is-active'}}"><a href = "#{{ ref_title|clean_class }}" aria-selected = "{{ i == 1 ? 'true' : 'false' }}">{{ ref_title }}</a></li>
                  {% endif %}
                {% endfor %}
              </ul>

              <div class = "tabs-content" data-tabs-content = "course-references-tabs">
                {% for i, value in node.field_references_par.value %}
                  <div id = "{{node.field_references_par[i].entity.field_title.value|clean_class}}" class = "tabs-panel{{ i == 0 ? ' is-active'}}">
                    {% autoescape false %}
                      {{ node.field_references_par[i].entity.field_content.value }}
                    {% endautoescape %}
                  </div>
                {% endfor %}
              </div>

            {% endif %}

          </div>

        {% endif %}

        {% if faculty|render %}

          <div id = "faculty" class = "tabs-panel course-faculty">

            <div class = "sections">

              {{ faculty }}

            </div>

          </div>

        {% endif %}

      </div>

    {% endif %}

    {% if related_courses|render %}

      {% set ancillary_1 = node.field_related_courses.fielddefinition.label %}
      {% set ancillary_2 = 'Guidance' %}
      {# set ancillary_2 = node.field_suggested_courses.fielddefinition.label #}

      <ul class = "sections sections-border accordion mobile-accordion stacked-tabs" data-accordion data-allow-all-closed = "true" data-multi-expand = "true">

        <li class = "section accordion-item" data-accordion-item>

          <a href = "#" class = "accordion-title show-for-small-only">{{ ancillary_1 }}</a>

          {% if related_courses|render %}

            <div class = "tiles mobile-accordion-content" data-tab-content>

              <h2 class = "field-label section-title hide-for-small-only">{{ ancillary_1 }}</h2>

              <div class = "list-items list-format-3">
                {{ related_courses }}
              </div>

            </div>

          {% endif %}

        </li>

        <li class = "section accordion-item" data-accordion-item>

          <a href = "#" class = "accordion-title show-for-small-only">{{ ancillary_2 }}</a>

          <div class = "tiles mobile-accordion-content" data-tab-content>

            <h2 class = "field-label section-title hide-for-small-only">{{ ancillary_2 }}</h2>

            <div class = "list-items list-format-1 list-type-guidance">
              {{ drupal_view('content_feed', 'guidance') }}
            </div>

          </div>

        </li>

      </ul>

      {{ drupal_view('content_feed', 'guidance_modal') }}

    {% endif %}

  {% else %}

    {{ content.body }}

  {% endif %}

</article>

Может быть, вы могли бы показать какой-то код, я думаю, никто не сможет ответить на этот вопрос на основе этой информации ...

digijay 27.12.2018 22:03

И мы не видим ничего, что вы упомянули в своем вопросе. Не видя хоть части кода, вы описываете этот вопрос совершенно неясно.

leymannx 30.12.2018 23:27

Совершенно верно. Я настолько новичок, что действительно не знал, что добавить, кроме самой веточки

Mat 02.01.2019 16:52
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
3
3
332
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Когда вы визуализируете шаблон веточки в контроллере, вы также можете передавать некоторые переменные в качестве данных. Если вы хотите показать эти данные в шаблоне ветки, вы вызываете их по имени внутри функций ветки и языковых конструкций.

В общем, все.

Я не могу вам больше помочь, потому что ваш вопрос очень общий.

Ответ принят как подходящий

Вам следует искать перехватчики препроцесса (функция yourmodule_preprocess ...). Если вы используете drupal8, вы можете установить новую переменную следующим образом:

$vars['myvar'] = 'test';

В веточке может называться так

{{ myvar }}

Важно: работает не во всех функциях. Я использую его для работы с функциями предварительной обработки, но благодаря @leymannx мы знаем, что он работает и с другими хуками:

"Not only preprocess hooks can pass variables to templates. Implement hook_theme and then in your controler theme the output and pass variables along to a template"

Другие вопросы по теме