【问题标题】:Configure velocity to render an object with something other than toString?配置速度以使用 toString 以外的东西渲染对象?
【发布时间】:2010-09-27 08:52:41
【问题描述】:

有没有办法将 Velocity 配置为使用 toString() 以外的方法将对象转换为模板中的字符串?例如,假设我正在使用带有 format() 方法的简单日期类,并且每次都使用相同的格式。如果我所有的速度代码都是这样的:

$someDate.format('M-D-yyyy')

是否有一些我可以添加的配置让我说一下

$someDate

相反? (假设我不能只编辑日期类并给它一个适当的 toString())。

如果有帮助的话,我会在使用 WebWork 构建的 web 应用的上下文中执行此操作。

【问题讨论】:

    标签: java templates velocity tostring webwork


    【解决方案1】:

    Velocity 允许使用类似 JSTL 的实用程序,称为 velocimacros:

    http://velocity.apache.org/engine/devel/user-guide.html#Velocimacros

    这将允许您定义一个宏,如:

    #macro( d $date)
       $date.format('M-D-yyyy')
    #end
    

    然后这样称呼它:

    #d($someDate)
    

    【讨论】:

    • 这也将其固定为默认格式。无需到处传递。确实是一个更好的主意。
    【解决方案2】:

    您还可以创建自己的 ReferenceInsertionEventHandler 来监视您的日期并自动为您进行格式化。

    【讨论】:

      【解决方案3】:

      哦,1.6+ 版本的 Velocity 有一个新的 Renderable 界面。如果您不介意将日期类绑定到 Velocity API,那么实现此接口,Velocity 将使用 render(context, writer) 方法(对于您的情况,您只需忽略上下文并使用 writer)而不是 toString( )。

      【讨论】:

        【解决方案4】:

        我也遇到过这个问题,我可以根据Nathan Bubna answer解决它。

        我只是想完成提供 link to Velocity documentation 的答案,它解释了如何使用 EventHandlers。

        在我的例子中,每次插入引用时,我都需要为 gson 库中的所有 JsonPrimitive 对象调用 Velocity 调用“getAsString”而不是 toString 方法。

        就像创建一个一样简单

        public class JsonPrimitiveReferenceInsertionEventHandler implements ReferenceInsertionEventHandler{
        
            /* (non-Javadoc)
             * @see org.apache.velocity.app.event.ReferenceInsertionEventHandler#referenceInsert(java.lang.String, java.lang.Object)
             */
            @Override
            public Object referenceInsert(String reference, Object value) {
                if (value != null && value instanceof JsonPrimitive){
                    return ((JsonPrimitive)value).getAsString();
                }
                return value;
            }
        
        }
        

        并将事件添加到 VelocityContext

        vec = new EventCartridge();
        vec.addEventHandler(new JsonPrimitiveReferenceInsertionEventHandler());
        
        ...
        
        context.attachEventCartridge(vec);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-07
          • 1970-01-01
          • 2013-04-10
          • 1970-01-01
          相关资源
          最近更新 更多