SOLVED

Trim string to x characters in Velocity

Go to solution
Phillip_Wild
Level 10

Hi all

 

Trying to do something which should be pretty straightforward - struggling! I'm trying to take a 18 character ID and take the first 15 characters from the left. 

 

I've looked up the string documentation and found $String.chop(), but using things like:

 

#set($id = "001jdhvie9584nvjdk")

#set($id = $id.chop(3))
###or###
#set($id = $String.chop($id, 3)

$id

 

Gives me simply $id as output. Trying logical methods such as "left" or .get(0,15) doesn't work either.

 

What am I missing? Thanks!

1 ACCEPTED SOLUTION
SanfordWhiteman
Level 10 - Community Moderator

 

 

#set( $first15ViaTruncate = $display.truncate($id,15,"") )

 

 

 

If you check first that you have at least 15 chars, you can use

 

#set( $first15ViaSubstring = $id.substring(0,15) )

 

 

If you do not check first, substring will throw a fatal error on unexpectedly short input. The Velocity tools are purposely more forgiving.

 

Don't know what String.chop you're referring to.

 

View solution in original post

4 REPLIES 4
SanfordWhiteman
Level 10 - Community Moderator

 

 

#set( $first15ViaTruncate = $display.truncate($id,15,"") )

 

 

 

If you check first that you have at least 15 chars, you can use

 

#set( $first15ViaSubstring = $id.substring(0,15) )

 

 

If you do not check first, substring will throw a fatal error on unexpectedly short input. The Velocity tools are purposely more forgiving.

 

Don't know what String.chop you're referring to.

 

Phillip_Wild
Level 10

Thanks Sanford! Works like a charm.

 

So I got chop from here: https://velocity.apache.org/engine/1.7/apidocs/org/apache/velocity/util/StringUtils.html. To be honest when I'm looking for methods I don't know I.....don't know where I should be looking! What is your master reference for methods? I feel that some Velocity code is available in Marketo and some isn't, but I don't know of a reference that exists. 

SanfordWhiteman
Level 10 - Community Moderator

StringUtils is an internal class, not a Velocity Tool. It isn't exposed in vanilla Velocity (you could export it into the context if you were in control of the Velocity engine, but for obvious security reasons we are not!).

 

The Generic Tools are the ones at https://velocity.apache.org/tools/devel/generic.html#tools, although not all are available within Marketo, for example Render, Class, Context, and Resource are not present and Xml is broken.

Phillip_Wild
Level 10

Thanks Sanford! I've bookmarked it.