簡體   English   中英

從 _entry.twig 中的 Twig 變量到外部腳本中的 Javascript 函數的數據

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

我創建了一個 _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)

目前,此腳本將創建一個傳單/osm 映射,然后基於:

// 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

好的,首先要指出一些指針,您可以向一個元素添加多個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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM