简体   繁体   English

从 _entry.twig 中的 Twig 变量到外部脚本中的 Javascript 函数的数据

[英]Data from Twig Variable in _entry.twig to Javascript Function in External Script

I have created a _layout.twig file which acts as my base to hold content on the page -> _layout.twig:我创建了一个 _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>

Through the control panel in craft CMS I created an entry that contains a table that has a series of coordinates (longitude and latitude values) and a lightswitch to toggle it on or off, along with some other general information for each entry that is created eg title, date, image, etc. on a separate tab.通过craft CMS 中的控制面板,我创建了一个条目,其中包含一个表,该表具有一系列坐标(经度和纬度值)和一个用于打开或关闭它的灯开关,以及创建的每个条目的一些其他一般信息,例如单独选项卡上的标题、日期、图像等。

The _entry.twig page extends _layout.twig -> _entry.twig: _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 %}

I was able to put together this small section in _entry.twig which looks at the table and if the lightswitch is set to 1, it outputs the corresponding latitude and longitude values in the row:我能够将这个小部分放在 _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 #}

These values are currently displaying on the front end entry page which will show the coordinates depending on which lightswitch toggle is active- which has allowed me to ensure that it is pulling the correct coordinates corresponding to the correct information.这些值当前显示在前端输入页面上,该页面将根据哪个灯开关切换处于活动状态显示坐标 - 这使我能够确保它正在拉动与正确信息相对应的正确坐标。

Now, I have an external js file linked which lives in local/craft/assets/js/*.js and contains this script -> scripts.js:现在,我链接了一个外部 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)

Currently, this script will create a leaflet/osm map and then based on:目前,此脚本将创建一个传单/osm 映射,然后基于:

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

will output a marker to the map (currently only works if I manually insert lat and long coordinates) which lives in my index.twig template file -> index.twig:将在我的 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 %}

What would be the best way to somehow use the以某种方式使用

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

variables from my _entry.twig file in my existing scripts.js file to place a marker(s) on the map which lives on the index.twig page?我现有的scripts.js 文件中_entry.twig 文件中的变量,以便在位于index.twig 页面上的地图上放置一个标记? I am still new to Craft and more so with Twig so I am still in the process of learning these things.我对 Craft 还是新手,对 Twig 更是如此,所以我仍在学习这些东西的过程中。

My folder structure is:我的文件夹结构是:

/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

Ok some pointers first, you can add multiple data-* attributes to one element, also id 's need to be unique.好的,首先要指出一些指针,您可以向一个元素添加多个data-*属性,而且id必须是唯一的。 So I'd suggest you'd swap up the twig template to the following:因此,我建议您将树枝模板交换为以下内容:

{% 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 %}

Then we need to adjust your javascript to be able to add multiple dots on the map.然后我们需要调整您的 javascript 以便能够在地图上添加多个点。
First remove the following line首先删除以下行

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

As you've defined the pointers in html we just need a selector that selects all the elements where the data-* attributes are defined in由于您已经在html定义了指针,我们只需要一个选择器来选择在其中定义了data-*属性的所有元素

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM