代码之家  ›  专栏  ›  技术社区  ›  Moss Collum

配置“速度”以使用除ToString之外的其他对象呈现对象?

  •  1
  • Moss Collum  · 技术社区  · 16 年前

    有没有一种方法可以配置Velocity来使用ToString()以外的东西来将对象转换为模板中的字符串?例如,假设我使用一个简单的日期类和一个format()方法,每次都使用相同的格式。如果我所有的速度代码都是这样的:

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

    有什么我可以补充的配置可以让我说

    $someDate
    

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

    如果这有帮助的话,我是在用WebWork构建的一个Webapp的上下文中这样做的。

    4 回复  |  直到 9 年前
        1
  •  1
  •   Nathan Bubna    16 年前

    您还可以创建自己的referenceInsertionEventHandler,它监视日期并自动为您设置格式。

        2
  •  1
  •   Mike    16 年前

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

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

    这将允许您定义如下宏:

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

    然后这样称呼它:

    #d($someDate)
    
        3
  •  1
  •   Nathan Bubna    16 年前

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

        4
  •  1
  •   Community CDub    7 年前

    我也面临着这个问题,我能够根据 Nathan Bubna answer .

    我只是想完成答案提供 link to Velocity documentation 这解释了如何使用事件处理程序。

    在我的例子中,每次插入引用时,我都需要为GSON库中的所有JSONPrimitive对象调用“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);