Accessing the Campaign ID, Campaign Run ID (!) and other elusive fields from Velocity

Update 2019-05-30: The code supplied here is superseded by this newer post.

Using the Lead ID from Velocity is trickier than you'd expect ($lead.Id is not accessible, even though there's a {{lead.Id}} token outside VTL).

And there are other interesting fields that are handy to have at send time — a couple of which aren't accessible any other way, giving Velocity a leg up.

Here's a quick snippet that creates a $marketoSend object with properties for Campaign ID, Campaign Run ID, and more:

#set( $marketoSend = {} )
#set( $delim = ":|-\d+$" )
#set( $values = $mktmail.xMarketoIdHdr.split($delim) )
## Campaign Run ID not relevant in Preview
#if( $values.size().equals(9) )
#set( $marketoIdKeys = "MunchkinId::CampaignId:StepId::AssetId::CampaignRunId:LeadId" )
#else
#set( $marketoIdKeys = "MunchkinId::CampaignId:StepId::AssetId::LeadId" )
#end
#set( $keys = $marketoIdKeys.split($delim) )
## loop interesting keys
#foreach( $key in $keys )
#if( !$key.isEmpty() )
#set( $marketoSend[$key] = $values[$foreach.index] )
#end
## append Program ID
#set( $marketoSend.ProgramId = $program.values().iterator().next() )
#end
Munchkin ID is ${marketoSend.MunchkinId}
Program ID is ${marketoSend.ProgramId}
Campaign ID is ${marketoSend.CampaignId}
Campaign Run ID is ${marketoSend.CampaignRunId}
Step ID is ${marketoSend.StepId}
Asset ID is ${marketoSend.AssetId}
Lead ID is ${marketoSend.LeadId}

You can then add the variables to a URL (also built in Velocity)
like so:

<a href="https://www.example.com/pagename.html?c=${marketoSend.CampaignId}&cr=${marketoSend.CampaignRunId}">Click me</a>