是否可以在 GSP 中声明函数?
如何在 GSP 中声明函数?我需要像 taglib 这样的东西,但在 GSP 内部声明 - 在外部并不重要
How can I declare a function inside GSP? I need something like taglib but declared inside GSP - it doesn't matter outside
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在 GSP 中定义方法。但是,如果您愿意,您可以使用匿名函数:D
示例:
尽管此示例没有太大意义,因为可以内联少量格式。对于视图的任何类型的额外逻辑,我会遵循OverZealous推荐并使用标签库。
You can't define methods in GSPs. But you can have anonymous functions if you want :D
Example:
Though this example doesn't make too much sense, as that little formatting could be inlined. For any kind of extra logic for the views, I would follow OverZealous recommendation and use a taglib.
不,只是不要这样做。这完全违背了普惠制的目的。 GSP 旨在处理视觉标记信息,而不是编程逻辑。直接在 GSP 中抛出函数将导致无法维护的混乱代码。
为什么不把它放在标签中?这就是标签的用途;它仅在您的 GSP 内使用并不重要。 GSP应该只包含简单的显示逻辑和输出内容。可重用代码应始终包含在标记库中或某种控制器或复杂逻辑服务中。
您没有提及您正在使用什么框架,例如 Gaelyk 或 Grails。 (除非您出于某种原因在服务器上使用纯 Groovy。)如果没有更多信息,则无法在这里推荐一个好的解决方案。
如果您在 GSP 中使用 JSP 样式标记 (
<% %>
),那么您可能做错了。如果您想要更好的答案,请提供有关编程环境、目标是什么以及原因(为什么您不想使用 taglib)的更详细信息。
No. Just don't do this. This is completely against the purpose of a GSP. The GSP is designed to handle visual markup information, not programming logic. Throwing functions directly within your GSP will lead to an unmaintainable mess of code.
Why won't you put it in a tag? This is what tags are for; it doesn't matter that it is only used within your GSP. The GSP should only contain simple display logic and output content. Reusable code should always be contained within a taglib or in some sort of controller or service for complex logic.
You don't mention what framework you are using, such as Gaelyk or Grails. (Unless you are using pure Groovy on the server for some reason.) There's no practical way to recommend a good solution here without more information.
If you are using JSP-style tags (
<% %>
) in your GSP, you are probably doing it wrong.If you want a better answer, please provide more detailed information about the programming environment, what the goal is, and why (for why you don't want to use a taglib).