Pass external variables

Sometimes you may want to pass variables to your embed without having to declare them inside Toucan Toco because it depends on the specific context of your application.

To do so, you can pass down your variables in embeds scripts:

<script async src="https://myinstance.toucantoco.com/scripts/embedLauncher.js?variables.my_var=\"foo\"" type="text/javascript"></script>

As you can see, you can add any key to our variables parameter. If you have to pass 2 parameters, for instance, youโ€™ll have to write:

<script async src="https://myinstance.toucantoco.com/scripts/embedLauncher.js?variables.my_var1=\"foo\"&variables.my_var2="[\"foo\", \"bar\"]"" type="text/javascript"></script>

Important

To support object and array type, weโ€™re parsing each variable. Make sure you have encoded it well using JSON.stringify

When it comes to passing down a lot of variables, including object and array, weโ€™re suggesting encoding a complete variables object and declaring all those extra variables into the extra key as follows:

var formattedVariables = JSON.stringify({
  extra: { // super important to put all your variables under the "extra" key
    varA: "simple_string",
    varB: 42,
    varC: {
      childrenKey: "str"
    },
    varD: ["itemA", "itemB"]
  }
})

// then used it programatically
var script = document.createElement('script');

script.src = `https://myinstance.toucantoco.com/scripts/embedLauncher.js?id=EMBED_ID&variables=${formattedVariables}`

// append it to your body or you parent div/component
document.body.appendChild(script);

// or in a template
<script async src=`https://myinstance.toucantoco.com/scripts/embedLauncher.js?id=EMBED_ID&variables=${formattedVariables}` type="text/javascript"></script>

Example

Setup in a story

After that, you can use your variables in the configuration of your story. Thanks to extraVariables you can template your variable inside the story. For example, you can set a contextual commentary.

IMAGE

Now youโ€™ve got an error because the variables arenโ€™t interpolated !

IMAGE

Note that you can display a default value to avoid that state.

IMAGE

You should now have default value interpolated.

IMAGE

Last updated