Outputting the value of dynamically created AMPScript variables

ampscriptdynamicmarketing-cloudssjs

In an email, I am using SSJS (I know, frowned upon) to parse out a JSON string.

%%[ var @resourceCount ]%% 
<script runat="server">
Platform.Load("Core","1");

var json = '[ { "Resource":"http://www.yahoo.com" }, { "Resource":"http://www.google.com" } ]'

// Parse JSON
var jsonObject = Platform.Function.ParseJSON(json);
var list = jsonObject;

// Loop through all items in the list (JSON)
for(var i = 0; i < list.length; i++ ) {
    var listItem = list[i];

    // Set List item info
    var resource = listItem['Resource'];

    // Set variabele name
    var loopNr = (i+1); // Add 1 because loop starts at 0
    var variableName = ("@resource"+loopNr); // Combine word title with number of loop

    // Write variabele to AMPscript for further processing
    Platform.Variable.SetValue(variableName, resource);
    Platform.Variable.SetValue("@resourceCount", loopNr)
}
</script>

As you can see towards the bottom of the script, I have:

var variableName = ("@resource"+loopNr); // Combine word title with number of loop
Platform.Variable.SetValue(variableName, resource);

So what we end up having is a number of AMPScript variables such as @resource1, @resource2, and so on. The unknown here is how many of these variables I will end up having. Could be 1, could be 10.

Once I have these variables created and set with data, I then try to output them into the email. That's where I'm having issues.

<table border="0" cellpadding="0" cellspacing="0" width="100%">
    %%[ for @counter = 1 to @resourceCount do  
       SET @tempValue = Concat('@resource', @counter)
     ]%%
      <tr>
       <td>
         %%=RedirectTo(@tempValue)=%%
       </td>
      </tr>
     %%[ next @counter ]%%
</table>

As one would probably expect, what's being output is the literal AMPScript variable – example: @resource1, @resource2, and so on. I need to be able to output the contents OF these variables. What am I missing here?

Best Answer

You need to set your @tempValue dynamically in this case and then correctly interpret the content of it by the TreatAsContent function. In the end, you would have something like this for immediate redirect -

<table border="0" cellpadding="0" cellspacing="0" width="100%">
    %%[ for @counter = 1 to @resourceCount do  
      @new_variable = TreatAsContent(CONCAT('%', '%[SET @tempValue = @resource', @counter, ']%', '%'))
     ]%%
      <tr>
       <td>
         %%=Redirect(@tempValue)=%%
       </td>
      </tr>
     %%[ next @counter ]%%
</table>

If you would want to set links on the page dynamically and then let users get redirected by clicking on them, then you need to use RedirectTo within the <a> HTML tag.

Related Topic