can Velocity set a default value for a variable when no value found in VelocityContext?

后端 未结 6 1307
野的像风
野的像风 2021-01-18 08:45

Velocity just print the tag name if no value was found in VelocityContext, ie, $name in my template file, but there is no value for \"name\" in VelocityContext, so just \"$n

相关标签:
6条回答
  • 2021-01-18 08:49

    There are a couple things you can do short of hacking Velocity internals. Have a look at this question.

    0 讨论(0)
  • 2021-01-18 09:00

    Create a velocimacro in your template:

    #macro(defaultValue $parm)  
    #if (!$!parm || $!parm == "")  
    i-like-will
    #else  
    $parm  
    #end  
    #end  
    

    And call it like this in the same template:

    #defaultValue($name)  
    

    Check Apache Velocity - Velocity User Guide for more info on velocimacros (and velocity in general).

    0 讨论(0)
  • 2021-01-18 09:03

    Google around for Velocity ReferenceInsertionEventHandler for a way to do it broadly.

    Consider the DisplayTool's alt() method for individual cases (part of the VelocityTools project)

    0 讨论(0)
  • 2021-01-18 09:05

    Not easily for all variables as far as I see, I only managed to do it for some variables specifically as follows:

    Template:

    #if ( !$somevar )
    #set ( $somevar = "mycontent" )
    #end
    
    Var is: $somevar
    

    Result:

    Var is: mycontent
    
    0 讨论(0)
  • 2021-01-18 09:11

    A little late to the party, but you could also perform a check when defining a variable. I had to compress this to one line to remove excess space in the output, but here is an example from one of my projects:

    #set ( $qlDefault = "qlinks" )
    #set ( $qlClass = "#if($sharedCtaImage.getChild('path').value != '/')$qlDefault#else$qlDefault full#end" )
    

    Default class is defined, then I check if another, specific value is filled in to determine if I keep the default class or append an additional class. This could also work for swapping out classes as well.

    0 讨论(0)
  • 2021-01-18 09:12

    For an empty default value, $!name will do. Otherwise,

    #{if}($name)${name}#{else}${default_value}#{end}

    See http://velocity.apache.org/engine/2.0/user-guide.html#quiet-reference-notation

    0 讨论(0)
提交回复
热议问题