关于php:将ACF地图数据传递到Timber主题中的树枝循环

Passing ACF map data to a twig loop in Timber theme

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

1
2
3
4
5
6
7
8
$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地图上为每个场所创建一个标记。由于我无法在树枝模板上执行此操作:

1
2
3
4
5
6
7
8
9
<?php
    $location = get_field('c_gmaps');
    $gtemp = explode ('|', $location);
    $coord = explode (',', $gtemp[1]);
    $lat = (float) $coord[0];
    $lng = (float) $coord[1];
?>

" data-lng="<?php echo $lng; ?>">

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

1
2
3
4
5
6
7
8
9
function render_markers(&$location) {
    var_dump($location);
    $gtemp = explode (',',  implode($location));
    $coord = explode (',', implode($gtemp));
    echo    '

    <p class="address">'
. $gtemp[0] . '' . the_title() . '</p>      
      '
;
}

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

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

这会产生重复错误:

Warning: Parameter 1 to render_markers() expected to be a reference,
value given in
/app/public/wp-content/plugins/timber-library/lib/Twig.php on line 310
string(8)"location" Warning: implode(): Argument must be an array in
/app/public/wp-content/themes/my_theme/page.php on line 122 Warning:
Illegal string offset 'lat' in
/app/public/wp-content/themes/my_theme/page.php on line 124

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


快速解决

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

此行...

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

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

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

大修复

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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文件中...

1
2
3
4
5
{% for item in venue %}
   
    <p class="address">{{ item.latitude }}{{ item.title }}</p>      
 
{% endfor %}