简体   繁体   English

Spring MVC,FreeMarker和自定义TagLib

[英]Spring MVC & FreeMarker & Custom TagLib

In a Spring MVC with FreeMarker environment, I have a custom TagLib that process a ftl template with data and write the result in the tag's JSP context. 在带有FreeMarker的Spring MVC环境中,我有一个自定义TagLib,它可以处理带有数据的ftl模板,并将结果写入标签的JSP上下文中。

When I call this tag from a resolved view (meaning from a template rendered by a controller) the behaviour is totally correct. 当我从已解析的视图(意味着从控制器渲染的模板)调用此标记时,此行为是完全正确的。

controller
    -> FTL
        -> TagLib

But when I call it from within a template to be processed by another instance of the same tag, I got an error (the tag is not defined) and when I add the #assign statement in my FTL, I also got an error (JspTagLibs is null). 但是,当我从模板中调用它并由同一标签的另一个实例处理时,出现错误(未定义标签),并且在FTL中添加#assign语句时,我也收到了错误(JspTagLibs一片空白)。

controller
    -> FTL
        -> TagLib
            -> FTL
                -> TagLib (crash!)

How could I solve this? 我该如何解决?

Thanks in advance 提前致谢

To call JSP tags from FTL, you need a special template context (data-model, in FTL terminology) that implements that. 要从FTL调用JSP标记,需要一个特殊的模板上下文(在FTL术语中为数据模型)来实现。 I assume Spring gives a such context for the initial call. 我假设Spring为初始调用提供了这样的上下文。 But if you start with a new template context (with a fresh freemarker.core.Environment actually) in the second case then you won't have the support. 但是,如果在第二种情况下从新的模板上下文开始(实际上是带有新的freemarker.core.Environment ),则将无法获得支持。 If you don't really need a fresh template context there, you could get the Environment higher up with static Environment.getCurrentEnvironment() , and then use Environment. include 如果你并不真的需要一个新的模板背景下出现,你可以得到的Environment更高了静态Environment.getCurrentEnvironment()然后使用Environment. include Environment. include to call the 2nd FTL. Environment. include调用第二个FTL。 However, then you will use the same set of template-created variables there as in the top-most FTL. 但是,您将在那里使用与最顶层FTL相同的模板创建的变量集。 (That can be improved somewhat if the 2nd FTL just defines a macro and calls it, because the macro can at least have locals.) So, you could just try reusing the dataModel from the higher Environment (using Environment.getDataModel() ) when you call the second FTL. (如果第二个FTL仅定义一个宏并对其进行调用,则可以有所改善,因为该宏至少可以具有本地变量。)因此,您可以在以下情况下尝试从更高的Environment重用dataModel (使用Environment.getDataModel() ):您称为第二个FTL。 I guess it should work... never tried it. 我想它应该可以工作...从未尝试过。

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

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