Revel: 将模板变量传递给URL

huangapple go评论74阅读模式
英文:

Revel: pass template var to url

问题

我想了解一下 url 辅助函数的工作原理。
例如,在我的模板中,我有以下代码:

<a href="{{url "Pages.IndexPages" ???}}">我的超级链接</a>

而在控制器中:

func (c Pages) IndexPages() revel.Result {
    ...
}

我需要的链接是:

http://localhost:9000/pages?page=1

我不想这样写:

func (c Pages) IndexPages(page int) revel.Result {

因为我想检查控制器是否包含参数 page。如何使用 url 辅助函数将我的模板变量添加到 c.Params.Query 中呢?

英文:

<br>
I want to understand how url helper works.
For example, in my template I have:

&lt;a href=&quot;{{url &quot;Pages.IndexPages&quot; ???}}&quot;&gt;my super url&lt;/a&gt;

and in controller:

func (c Pages) IndexPages() revel.Result {
    ...
}

I need url like

http://localhost:9000/pages?page=1

I don't want to write:

func (c Pages) IndexPages(page int) revel.Result {

because I want to check if the controller contains the param page.<br>
How to add my template var to c.Params.Query with the url helper?

答案1

得分: 1

Revel url helper code in template.go

// 返回一个能够调用给定控制器方法的URL:
// "Application.ShowApp 123" => "/app/123"
func ReverseUrl(args ...interface{}) (template.URL, error) {

我们需要更新手册,提供关于这个模板函数的信息,但是你可以在上面的链接和代码中看到它的使用方式。你传递一个带有参数的控制器和动作,它会创建一个与之匹配的template.URL对象。

看起来你对于url助手的工作原理不感兴趣(尽管这是你问的问题)。你想知道如何将page变量传递给模板?在你的控制器中,你需要通过c.RenderArgs["page"] = page来传递page。然后你可以在模板中引用它:<a href="{{url "Pages.IndexPages" .page}}">my super url</a> Revel模板文档

正如你所指出的,如果你不想使用参数绑定功能,你可以手动获取page的值:page := c.Params.Query.Get("page")

英文:

Revel url helper code in template.go

// Return a url capable of invoking a given controller method:
// &quot;Application.ShowApp 123&quot; =&gt; &quot;/app/123&quot;
func ReverseUrl(args ...interface{}) (template.URL, error) {

We need to update the manual with information about this template function, but you can see in the link and code above how it's intended to be used. You pass it a controller and action with parameters and it creates a template.URL object with the matching route.

It seems you're not interested in how the url helper works (though that's what you asked). You want to know how to pass the page variable to the template? In your controller you need to pass page via c.RenderArgs[&quot;page&quot;] = page. Then you can reference it in your template: &lt;a href=&quot;{{url &quot;Pages.IndexPages&quot; .page}}&quot;&gt;my super url&lt;/a&gt; Revel Template Doc.

As you noted, you can manually get the value for page with page := c.Params.Query.Get(&quot;page&quot;) if you don't want to use the parameter binding feature.

huangapple
  • 本文由 发表于 2014年7月24日 20:30:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/24933770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定