如何输出
一些 html 标签将给定属性的“任何”值解释为“true”->我想到了选项标签。
我经常最终会做这样的事情:
<c:choose>
<c:when test="${isSelected}"/>
<option selected="true">Opt1</option>
</c:when>
<c:otherwise/>
<option>Opt1</option>
</c:otherwise>
</c:choose>
我知道我可以声明一个自定义来封装此行为,但是也会变得非常难看,除非我用 java 对其进行编码。
有没有更聪明的方法来做到这一点?
A few html tags interpret "any" value of a give attribute as "true" -> option tags come to mind.
I frequently end up doing something like this:
<c:choose>
<c:when test="${isSelected}"/>
<option selected="true">Opt1</option>
</c:when>
<c:otherwise/>
<option>Opt1</option>
</c:otherwise>
</c:choose>
I know I can declare a custom to encapslate this behaviour but that also gets pretty ugly, unless I code it in java.
Is there a smarter way to do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
解决此问题的一种方法是使用自定义标签。
我喜欢 JSP2X 转换器采用的方法,在 WEB-INF/tags 文件夹中定义自定义标记,以便您执行此操作:
更紧凑的方法可能是专门为执行正确操作的选项创建自定义标记,采用selected 属性的布尔值,如果为 true,则发出 selected="selected" 属性,否则不发出。这会更紧凑一些:
One way to approach this would be to use custom tag(s).
I like the approach that the JSP2X converter takes, defining custom tags in your WEB-INF/tags folder that let you do this:
A more compact approach might be to create a custom tag specifically for an option that did the right thing, taking a boolean value for the selected attribute, emitting a selected="selected" attribute if it's true, not otherwise. This would be a bit more compact:
编写
是的,更聪明的方法是按照 XHTML 的要求来
。我知道这不是你真正要问的:-)我认为你的方法很好,或者你可以使用条件表达式代替:
它更短,但不一定更漂亮。
Yes, a smarter way would be to write
as that's what's mandated by XHTML.
I know that's not what you're really asking :-) I think your way is fine or you can use a conditional expression instead:
It's shorter though not necessarily prettier.
对于
并像这样使用它:
krosenvold,我不同意这很丑......也许很烦人,但我实际上很高兴我不必为此编写任何代码。一旦定义了标签,您的 JSPX 就会变得更加整洁。此外,我根本不认为这有什么捷径。
For the
<select><option selected="selected">
problem, I decided I wouldn't mind a bit of verboseness, if it was only one-time-verboseness... so I created a tag document (.tagx) in/WEB-INF/tags/select.tagx
like so:and use it like so:
krosenvold, I don't agree that this is ugly... maybe annoying but I'm actually glad I didn't have to write any code for this. Once you've defined the tag, your JSPXs become much tidier. Besides, I simply don't think there is a short cut for this.
还有另一种方法可以解决这个问题。这有点像黑客,但可以替代使用标签库或选择复制标签的位置,我发现效果很好。
您可以在 jstl set 标记内构建标记作为值,如下所示:
然后,无论您想要该标记,您都可以像这样输出:
There is another way to get around this. It's a bit of a hack but an alternative to using a taglib or a choose where you duplicate the tag which I discovered works quite well.
You can build the tag inside a jstl set tag as the value, something like this:
Then, wherever you want that tag, you just output like this: