简体   繁体   English

创建自定义GSP标签,而无需编写Groovy代码

[英]Create custom GSP tag without writing Groovy code

Is it possible to create a custom GSP tag without writing Groovy code and embedding my HTML in the code (ie more of a JSP style way of creating a custom tag)? 是否可以在不编写Groovy代码并将我的HTML嵌入代码的情况下创建自定义GSP标签(即,更多的JSP样式创建自定义标签的方式)?

I have a menu that consists of a bunch of items something like: 我有一个菜单,其中包含很多项目,例如:

<li class="menu-item">
  <g:link controller="someController" action="someAction" id="123">
    My Item Text
  </g:link>
</li>

I would like to create a new GSP tag to simplify my pages since it will be repeated multiple times. 我想创建一个新的GSP标签来简化我的页面,因为它将重复多次。 So, I'd like to create something like: 因此,我想创建以下内容:

<my:menuitem controller="someController" action="someAction" id="123" text="My Item Text"/>

I know that I can create a custom taglib and create the tag using Groovy code. 我知道我可以创建一个自定义taglib并使用Groovy代码创建该标签。 However I really don't like the idea of embedding HTML into a Groovy file. 但是我真的不喜欢将HTML嵌入Groovy文件中的想法。 In the past I have created JSP taglibs in essentially a JSP file without writing Java code. 过去,我实际上是在JSP文件中创建JSP taglib的,而无需编写Java代码。 So far looking at the documentation for Grails I haven't seen a similar style. 到目前为止,在查看Grails的文档时,我还没有看到类似的样式。

As a side note, can custom JSP tags be used within GSP? 附带说明一下,可以在GSP中使用自定义JSP标签吗?

You can do this with a template via the render tag, as explained in the "Views and Templates" section of the docs. 您可以通过render标签使用template来执行此操作,如文档的“视图和模板”部分所述。 Its worth noting you name the template file with a leading underscore but you refer to it in the render tag without the underscore. 值得注意的是,您使用一个下划线来命名模板文件,但是在render标签中引用该文件时不使用下划线。

The other alternative is to use a custom taglib as you described but to create your HTML with the Groovy MarkupBuilder . 另一种选择是使用您描述的自定义taglib,但使用Groovy MarkupBuilder创建HTML。 It takes a bit of getting used to (syntax is a bit strange) but once you've done a few times it becomes second nature. 这需要一点时间来适应(语法有点奇怪),但是一旦完成几次,它就会成为第二天性。

The only way I can see to do what you want to do without a Taglib is to use g:render and pass in your values into the model attribute. 在没有Taglib的情况下,我可以看到的唯一方法是使用g:render并将您的值传递到model属性中。 Like this: 像这样:

<g:render template="myTemplate" model="[controller: 'someController', action: 'someAction', id: 123, text: 'My Text Item']" />

Then in your actual template you will have the following: 然后,在您的实际模板中,将具有以下内容:

<li class="menu-item">
  <g:link controller="${controller}" action="${action}" id="${id}">
    ${text}
  </g:link>
</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM