问题描述

在 Golang 中,是否可以在更新变量时刷新模板的一部分?例如,我们可以在 Angular.js 中找到这一点.

In Golang, it is possible to refresh a part of a template when a variable is updated ? This is something that we can find in Angular.js for instance.

基本上在我的代码中,我通过 ajax 中的邮政编码查找地址,它显示我为此邮政编码找到的地址列表.

Basically in my code, I lookup adresses by a postcode in ajax, which display my list of addr found for this postcode.

这是模板示例:

此时,ajax 调用了一个 GO 例程.我不想在 JS 中获取结果并从 ajax 调用的结果构建 html.

At the moment, the ajax calls a GO routine. I don't want to get the result in the JS and build the html from the result of the ajax call.

如果可能,我想只更新 Addresses 值(它是一个数组),因为我已经动态构建了 addr 列表.

I would like, if possible, to update only the Addresses value (it's an array) as I already build the list of addr dynamically.

有什么线索吗?

推荐答案

模板引擎不支持这种现成的.

The template engine does not support this out-of-the-box.

所以你必须自己实现它.这并不难.以下是您应该遵循的步骤:

So you have to implement it yourself. It's not that hard. Here are the steps you should follow to achieve it:

{{define "name"}}{{template "name"}}{{block "name" pipeline}} T1 {{end}}
{{define "name"}}{{template "name"}}{{block "name" pipeline}} T1 {{end}}
w http.ResponseWriter
w http.ResponseWriter

请注意,您可以使用 1 个处理程序来执行完整"页面模板和仅 Addressees 模板(例如,根据 URL 参数进行决定),或者您可能有 2 个不同的处理程序,这完全取决于您.

Note that you may use 1 handler to execute both the "full" page template and only the Addressees template (e.g. deciding based on a URL parameter), or you may have 2 distinct handlers, it's really up to you.

现在在客户端,当您想要刷新/重新呈现 Addressees 时,对仅执行和呈现 Addressees 模板的处理程序进行 AJAX 调用.

Now at client side when you want to refresh / rerender the Addressees, make an AJAX call to the handler that only executes and renders the Addressees template.

当这个 AJAX 调用完成时,您可以简单地使用 AJAX 调用的响应文本来替换 Addressees 的包装标记的 HTML 内容.

When this AJAX call completes, you may simply use the response text of the AJAX call to replace the HTML content of the wrapper tag of Addressees.

它可能看起来像这样:

var e = document.getElementById("addressees");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        e.outerHTML = xhr.responseText;
    }
}
xhr.open("GET", "path-to-addresses-render", true);
try {
    xhr.send();
} catch (err) {
    // handle error
}

Gowut(这是一个用于构建单页网络的网络框架使用纯 Go 的应用程序所做的事情类似于只更新网页的一部分而不重新加载整个页面(尽管它在后端不使用模板).(披露:我是 Gowut 的作者.)

js.gorerenderComp()
js.gorerenderComp()

这篇关于golang更新变量时动态刷新模板的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!