【问题标题】:Data from Twig Variable in _entry.twig to Javascript Function in External Script从 _entry.twig 中的 Twig 变量到外部脚本中的 Javascript 函数的数据
【发布时间】:2021-01-19 23:13:50
【问题描述】:

我创建了一个 _layout.twig 文件,作为我在页面上保存内容的基础 -> _layout.twig:

<!DOCTYPE html>
<html lang="{{ craft.app.language }}">
  <head>
    <meta content="IE=edge" http-equiv="X-UA-Compatible" />
    <meta charset="utf-8" />
    <title>
      {{ siteName }}
    </title>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
      name="viewport" />
    <link rel="stylesheet"
      href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"
      integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
      crossorigin="" />
    {% includeCssFile siteUrl ~ 'assets/css/style.css' %}
  </head>
  <body>
    {% include '_includes/nav' %}
    <div>
      {% block content %}

      {% endblock %}
    </div>
    <footer class="main-footer">
      <div class="footer-wrapper">
        {{ exampleInformation.exampleDescription|markdown }}
        <p>
          &copy; {{ now|date('Y') }}, <a href="https://craftcms.com">Lorem Ipsum</a>
        </p>
      </div>
    </footer>
    <script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"   integrity="sha512QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin=""></script>
    {% includeJsFile siteUrl ~ 'assets/js/scripts.js' %}
  </body>
</html>

通过craft CMS中的控制面板,我创建了一个条目,其中包含一个表格,该表格具有一系列坐标(经度和纬度值)和一个用于打开或关闭它的灯开关,以及每个条目的一些其他一般信息被创建,例如标题、日期、图像等在单独的选项卡上。

_entry.twig 页面扩展了 _layout.twig -> _entry.twig:

{% extends '_layout' %}

{% set featureImage = {
  mode: 'crop',
  width: 600,
  height: 600,
  quality: 90
} %}

{% block content %}
  <div class="entry__container">
    <div class="entry__wrapper">
      <div class="entry__title">
        <h1>
          {{ entry.title }}
        </h1>
      </div>

      <div class="entry__image">
        {% if entry.featureImage|length %}
          {% for image in entry.featureImage.all() %}
            <img src="{{ image.getUrl(featureImage) }}"
              alt="{{ image.title }}" />
          {% endfor %}
        {% endif %}
      </div>

      <div>
        {% for block in entry.exampleContent.all() %}
          <div class="entry__description">
            {% if block.type == 'text' %}
              {{ block.text }}
            {% elseif block.type == 'image' %}
              {% for image in block.image.all() %}
                <img src="{{ image.url }}" alt="{{ image.title }}" />
              {% endfor %}
            {% endif %}
          </div>
        {% endfor %}
      </div>

      {# display post categories #}
      {% if entry.exampleCategories|length %}
        <div class="entry__category">
          <p>
            Categories
          </p>
          {% for category in entry.exampleCategories.all() %}
            <a href="{{ category.url }}">{{- category.title -}}</a>
          {% endfor %}
        </div>
      {% endif %}

      {# display table info #}
      {% if entry.lotInfo|length %}
        <div class="entry__coordinate">
          <ul>
            {% for row in entry.lotInfo %}
              {% if row.createNewEntry == '1' %}
                <li>
                  <div data-latCoordinate="{{ row.latitude }}"
                    id="latCoordinate">
                    {{ row.latitude }}
                  </div>,<div data-lngCoordinate="{{ row.longitude }}"
                    id="lngCoordinate">
                    {{ row.longitude }}
                  </div>
                </li>
              {% endif %}
            {% endfor %}
          </ul>
        </div>
      {% endif %}
      {# end table info #}
    </div>
  </div>
{% endblock %}

我能够将这个小部分放在 _entry.twig 中查看表格,如果灯开关设置为 1,它会在行中输出相应的纬度和经度值:

{# display table info #}
      {% if entry.lotInfo|length %}
        <div class="entry__coordinate">
          <ul>
            {% for row in entry.lotInfo %}
              {% if row.createNewEntry == '1' %}
                <li>
                  <div data-latCoordinate="{{ row.latitude }}"
                    id="latCoordinate">
                    {{ row.latitude }}
                  </div>,<div data-lngCoordinate="{{ row.longitude }}"
                    id="lngCoordinate">
                    {{ row.longitude }}
                  </div>
                </li>
              {% endif %}
            {% endfor %}
          </ul>
        </div>
      {% endif %}
      {# end table info #}

这些值当前显示在前端输入页面上,该页面将根据激活的灯开关切换显示坐标 - 这使我能够确保它正在拉动与正确信息相对应的正确坐标。

现在,我有一个链接的外部 js 文件,它位于 local/craft/assets/js/*.js 并包含此脚本 -> scripts.js:

//Set initial map view

var map = L.map('map', { scrollWheelZoom: false }).setView(
  [50.4205, -104.52],
  15,
)

//Initialize the tilemap
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  minZoom: 14.5,
  attribution:
    '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map)

// Set location array
var locations = [{ lat: 'SOME LATITUDE COORDINATE', lng: 'SOME LONGITUDE COORDINATE' }]

function addToMap(locationArray) {
  //Iterate through array object
  ;[].forEach.call(locationArray, function (location) {
    var marker = L.marker([location.lat, location.lng]).addTo(map)
  })
}
//Show markers
addToMap(locations)

目前,这个脚本会创建一个leaflet/osm map,然后基于:

// Set location array
var locations = [{ lat: '(SOME LATITUDE VALUE)', lng: '-(SOME LONGITUDE VALUE') }];

将向地图输出一个标记(目前仅在我手动插入经纬度坐标时才有效),它位于我的 index.twig 模板文件中 -> index.twig:

{% extends '_layout' %}
{% set posts = craft.entries.section('example').all() %}
{% block content %}
  <div class="background-test">
    <div id="map"></div>
  </div>
  <div class="main-container">
    <div class="main-wrapper">
      <h1 class="example-title">
        Some Title
      </h1>
      <div class="category-list">
        {% set entries = craft.entries.limit(null) %}
        {% for category in craft.categories.relatedTo(entries).order(
          'title asc'
        ) %}
          {% set entryCount = entries.relatedTo(category).total() %}
          <a href="{{ category.url }}">
            {{- category.title -}}<span class="count-number">({{ entryCount }})</span>
          </a>
        {% endfor %}
      </div>
      {% include '_includes/listing' with {
        posts: posts
      } only %}
    </div>
  </div>
{% endblock %}

以某种方式使用的最佳方法是什么

{{ row.latitude }}, {{ row.longitude }}

我现有 scripts.js 文件中的 _entry.twig 文件中的变量以在位于 index.twig 页面上的地图上放置一个标记?我对 Craft 还很陌生,对 Twig 更是如此,所以我仍在学习这些东西。

我的文件夹结构是:

/assets
   /css
   /js
      scripts.js
/templates
   /includes
   /blog
      _category.twig
      _entry.twig
       index.twig
   _layout.twig
   index.html

Any help would be greatly appreciated!

Thank you

【问题讨论】:

  • 这能回答你的问题吗? Twig variable in extern js file
  • 请注意,重复答案的关键部分是,如果您的 JS 库期望 lat, long 作为字符串而不是 int,{{ row.latitude }}, {{ row.longitude }} 不等于 '{{ row.latitude }}', '{{ row.longitude }}'(注意引号'!)。
  • 我想我的问题最终是,我将如何传递两个变量:{{ row.latitude }}, {{ row.longitude }} 在我的 _entry.twig 模板页面中定义,它扩展了 _layout.twig到位于 web/scripts.js 中的 javascript 函数?
  • 好吧,我已经在欺骗中更新了我的答案,为您提供两种方式
  • @DarkBee 谢谢你的建议!我已经查看了那个帖子,不幸的是,我仍然没有成功。我已经更新了我上面的问题,以包括我目前拥有的所有代码以及文件夹结构,希望能阐明我哪里出错了。您可以提供的任何建议将不胜感激。基本上,我可以让 {{ row.latitude }} 和 {{ row.longitude }} 控制台记录入口页面本身的值,但似乎无法弄清楚如何将它们传递给我的外部 js 并显示它在索引页面上呈现的地图上。再次感谢您!

标签: javascript variables dynamic twig craftcms


【解决方案1】:

先确定一些指针,你可以为一个元素添加多个data-* 属性,同时id 需要是唯一的。所以我建议你将树枝模板换成以下:

{% if entry.lotInfo|length %}
<div class="entry__coordinate">
  <ul>
    {% for row in entry.lotInfo %}
      {% if row.createNewEntry == '1' %}
        <li data-latCoordinate="{{ row.latitude }}" data-lngCoordinate="{{ row.longitude }}">
            {{ row.latitude }}, {{ row.longitude }}
        </li>
      {% endif %}
    {% endfor %}
  </ul>
</div>
{% endif %}

然后我们需要调整您的 javascript 以便能够在地图上添加多个点。
首先删除以下行

// Set location array
var locations = [{ lat: 'SOME LATITUDE COORDINATE', lng: 'SOME LONGITUDE COORDINATE' }]

正如您在 html 中定义的指针,我们只需要一个选择器来选择其中定义了 data-* 属性的所有元素

<script>
document.querySelectorAll(".entry__coordinate ul li").forEach(row => {
    addToMap({ 'lat': row.dataset.latcoordinate, 'lng' : row.dataset.lngcoordinate, });
});
</script>

【讨论】:

  • 谢谢!我进行了更改并将您提供的脚本添加到 my_entry.twig 页面下的 reworked 部分,同时从我的 script.js 文件中删除了 'var locations=[]'。但是,似乎某处仍然存在断开连接。当_entry。树枝页面打开时会抛出错误“未定义 addToMap”和“未找到地图容器”,并且在带有地图容器 _layout.twig 的页面上根据我的外部 js 文件抛出“未定义位置”。从地图容器所在的 _entry.twig > scripts.js > index.twig (map) 获取数据似乎仍然存在问题
猜你喜欢
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多