【问题标题】:Can i pass php variables when including a partial?我可以在包含部分时传递 php 变量吗?
【发布时间】:2018-03-09 06:51:03
【问题描述】:

我是 OctoberCMS 的新手,所以我不太了解。 我阅读了 10 月份的文档,并且知道如何在以静态方式使用局部变量时传递变量:

{% partial "location" city="Vancouver" country="Canada" %}

我的问题是我需要使用 php 或 js 变量。假设我有一个输入字段,用户在其中写入一个 ID,然后在按下按钮后我想将 ID 传递给部分。我正在尝试做这样的事情:

{% partial "location" city=$city country=$country %}

有人可以帮助我吗?谢谢。

【问题讨论】:

    标签: javascript php twig partials octobercms


    【解决方案1】:

    您是否尝试过此处记录的这种方法? https://octobercms.com/docs/cms/partials#partial-variables

    {% partial "location" city=city country=country %}
    

    编辑

    顺便说一句,您需要在 onStart 函数中定义页面变量。

    url = "/blah"
    layout = "default"
    ==
    <?
    function onStart()
    {
        $this['country'] = ...;
        $this['city'] = ...;
    }
    ?>
    ==
    {% partial "location" city=city country=country %}
    

    编辑

    您是否阅读过有关 AJAX 的部分? https://octobercms.com/docs/ajax/introduction

    更具体地说 - https://octobercms.com/docs/ajax/update-partials#pushing-updateshttps://octobercms.com/docs/ajax/update-partials#update-definition

    编辑

    只需重新阅读您的原始问题,您就会询问绑定到表单元素,而不是 AJAX。

    看看 JS API - https://octobercms.com/docs/ajax/javascript-api#javascript-api

    我认为你可以这样做:

    &lt;form onsubmit="$(this).request('onMyProcessingMethod'); return false;"&gt;

    $('form').request('onMyProcessingMethod', {
        update: {myPartialName: '.whereIWantTheOutputToGo'},
        data: {country: 'Canada'} // Not 100% sure how to access form input; maybe ID selector
    })
    

    【讨论】:

    • 是的,但是在这种情况下国家应该是一个树枝变量,我不知道如何使用它们,我试过但没有结果。
    • 根据本页底部的 blub(“访问逻辑”-octobercms.com/docs/markup/templating),Twig 应该可以访问 PHP 变量;当然没有美元符号。
    • 在调用您的部分之前,尝试输出一个变量并查看它是否显示 - {{ country }}
    • 谢谢,它正在工作,但如果我想更改变量怎么办?我读到我必须使用 onStart() 但现在我使用 ajax 表单来确定值,所以它不能工作。我应该在帖子中使用普通表格吗?还是有更好的解决方案?
    • 我认为这可能是实现该目标的错误方法,也许您必须查看组件而不是部分
    【解决方案2】:

    您可以通过这种方式在部分内部使用变量:

    <p>Country: {{ country }}, city: {{ city }}.</p>
    

    【讨论】:

    • 是的,但是 OP 需要先将变量传递给局部变量,然后才能在那里访问它们。
    • 有一个专用函数 onStart() 可以帮助我们在脚本访问变量之前定义变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多