How to fetch code snippet with AMPScript
If you have ever experienced troubles when referring to your content block within another resource, either an email template or a cloud page, using ContentBlockBy AMPScript functions, I will show you a hopefully better way to include your snippets in your content.
Dynamic content creation and personalization within Salesforce Marketing Cloud, can often grapple developers with the challenge of making their AMPScript code not only functional but also easily maintainable. One of the key considerations, for me and hope for many others, is how to reference content blocks in a way that is both human-readable and robust against changes.
ContentBlockByName
This function retrieves content from a specified Content Block, with an optional Impression Region wrapping.
Arguments: ContentBlockByName(path, impressionRegion, throwError, defaultContent, statusCode)
Parameters:
path
(String, required): Full path of the content block to retrieve.impressionRegion
(String, optional): Name of the Impression Region associated with this Content Area.throwError
(Boolean, optional): Returns an error if the Content Area cannot be found.defaultContent
(String, optional): Default content returned if an error occurs during retrieval.statusCode
(Number, optional): Numeric status code; 0 for success, -1 if content is not found or empty.
%%[ set @contentBlockName = "Content Builder\mycontentblock" set @content = ContentBlockByName(@contentBlockName, "Greeting", 0, "", @statusCode) if @statusCode == 0 then output(v(@content)) endif ]%%
ContentBlockById
Same function with identical arguments as the previous function, but instead of a path, we have to provide the ID of the content block.
%%[ set @contentBlockID = 12345 set @content = ContentBlockByName(@contentBlockID, "Greeting", 0, "", @statusCode) if @statusCode == 0 then output(v(@content)) endif ]%%
ContentBlockByKey
Last but not least, we can request a content block by its external key, which we can modify to our needs, making it readable and understandable for any code readers passing by.
%%[ set @contentBlockKey = 'mycontentblock' set @content = ContentBlockByKey(@contentBlockKey, "Greeting", 0, "", @statusCode) if @statusCode == 0 then output(v(@content)) endif ]%%
So which one is the best?
I personally, and hopefully many others, find the best function to use is ContentBlockByKey
for several reasons:
- you can move the block around without breaking the template as opposed to
ContentBlockByName
- human-readable text in your code without the need for any lookups as opossed to
ContentBlockBy
Id