How to use Plugin jsencode in IBM WCM 8.5

carita-feliz

The problem

JSON is the current format by excellence for sending messages and getting information via web services. But we usually have a big problem because of special characters like double quotes, let’s go back for a moment to remember how a well-formatted JSON looks:

{
"field" : "value"
}

As you know, previous is a well-formatted JSON block, but what happen if the “value” is something like this:

{
"title" : "I am creating the "definitive" guide to use encoding in WCM"
}

Previous code is going to fail for sure! and that’s because we are using double quotes in the “definitive” word as the value for the title, which breaks the well-formatted JSON we created.

The solution

Ok, now what can we do if we have IBM WCM 8.5 version? Easy, just add the jsencode plugin in next format:

{
"field" : "[Plugin:jsencode enc="js" value="SOMETHING_TO_ENCODE"]"
}

For example if you want to encode the title of pieces of content:

{
"title" : "[Plugin:jsencode enc="js" value="[Property context='autofill' type='content' field='title']"]"
}

What kind of output will we get using this plugin?

{
"title" : "I am creating the "definitive" guide to use encoding in WCM"
}

Finally, if you need to encode many fields, this is more complex example which encodes the author, title, siteTitle and the summary.

{
      "date":"[Property context="autofill" type="content" format="relative" field="publishdate"]",
      "author":"[Plugin:jsencode enc="js" value="[Property context='autofill' type='content' field='authors']"]",
      "title":"[Plugin:jsencode enc="js" value="[Property context='autofill' type='content' field='title']"]",
      "url":"[Placeholder tag="href"]",
      "overrideURL": "",
      "linkType":"",
      "thumbnail":"[Element context="autofill" type="content" key="thumbnail" format="url"]",
      "siteTitle":"[Plugin:jsencode enc="js" value="[Property context='autofill' type='top' field='title']"]",
      "siteURL":"[URLCmpnt context="autofill" type="parent" mode="standalone"]",
      "summary":"[Plugin:jsencode enc="js" value="[Element context='autofill' type='content' key='summary']"]"
}

Explanation

The principle behind this is simple: for every single JSON value using the plugin jsencode, WCM -behind the scenes- is going to execute a procedure to encode the HTML before rendering the page, which solves the issue in a great way!

That’s it for today, don’t forget to be happy with your code!

Añade un Comentario

Leave a Reply

Your email address will not be published. Required fields are marked *