个性化阅读
专注于IT技术分析

将ACF地图数据传递到Timber主题中的twig循环

点击下载

我继承了一个使用自定义Timber主题的网站, 并对如何将常规PHP中的解决方案转换为Twig语法感到非常困惑。我需要使用自定义帖子类型(地点)在Google地图上显示多个标记。我有一个工作查询来收集所有已发布的场地:

$venue_query = array(
    'post_type' => 'venue', 'posts_per_page' => -1, 'post_status' => 'publish'
);

$context['venue'] = Timber::get_posts( $venue_query );
Timber::render( 'beesknees-participating-venues.twig', $context );

我正在尝试遵循这个ACF论坛主题, 以便循环浏览所有场所并在Google地图上为每个场所创建一个标记。由于我无法在树枝模板上执行此操作:

<?php
    $location = get_field('c_gmaps');
    $gtemp = explode ('|', $location);
    $coord = explode (', ', $gtemp[1]);
    $lat = (float) $coord[0];
    $lng = (float) $coord[1];
?>

<div class="marker" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">

我尝试在page.php文件中编写一个函数:

function render_markers(&$location) {
    var_dump($location);
    $gtemp = explode (', ', implode($location));
    $coord = explode (', ', implode($gtemp));
    echo    '<div class="marker" data-lat="' . $location[lat] .'" data-lng="'. $location[lng] .'">

    <p class="address">' . $gtemp[0] . '<a href="' . the_permalink() .'" rel="bookmark" title="Permanent Link to '. the_title_attribute() .'">' . the_title() . '</a></p>       
      </div>';
}

然后在我的树枝模板中使用它:

{% for item in venue %}
    {% set location = item.get_field('google_map')  %}
    {{ function('render_markers', 'location') }}
{% endfor %}

生成重复错误:

警告:参数render_markers()的1应该是参考, 在/app/public/wp-content/plugins/timber-library/lib/Twig.php中第310行string(8)” location”中给出的警告:爆裂():参数必须是第122行的/app/public/wp-content/themes/my_theme/page.php中的数组警告:/ app / public / wp-content / themes / my_theme /中的字符串偏移量’lat’不合法第124页的page.php

我想我已经接近了, 但不确定。我在Twig或Timber文档中找不到足够具体的示例。任何帮助将不胜感激。


#1


快速解决

这感觉很棘手, 但是(可能)可以快速解决

这条线…

{{ function('render_markers', 'location') }}

…只是将字符串” location”发送到函数。你需要刚创建的Twig变量。尝试将其更改为…

{{ function('render_markers', location) }}

大修复

这是更”优雅的解决方案”

<?php

class Venue extends Timber\Post {

    function coordinates() {
        $location = $this->get_field('c_gmaps');
        $gtemp = explode ('|', $location);
        $coord = explode (', ', $gtemp[1]);
        return $coord;

    }

    function latitude() {
        $coord = this->coordinates();
        $lat = (float) $coord[0];
        return $lat;
    }

    function longitude() {
        $coord = this->coordinates();
        $lng = (float) $coord[1];
        return $lng;
    }

}


/* at the bottom of the PHP file you posted: */

$context['venue'] = Timber::get_posts( $venue_query, 'Venue' );
Timber::render( 'beesknees-participating-venues.twig', $context );

在你的Twig文件中…

{% for item in venue %}
    <div class="marker" data-lat="{{ item.latitude }}" data-lng="{{ item.longitude }}">
    <p class="address">{{ item.latitude }}<a href="{{ item.link }}" rel="bookmark" title="Permanent Link to {{ item.title | escape }}">{{ item.title }}</a></p>       
  </div>
{% endfor %}
赞(0)
未经允许不得转载:srcmini » 将ACF地图数据传递到Timber主题中的twig循环

评论 抢沙发

评论前必须登录!