Object-like params in shortcodes

I have a shortcode which generates a stiff HTML structure with multiple elements positioned in specific places. I am looking for ways to pass params which would have a structure, similar to this json:

key: {
  name: Name,
  value: Value

and to pick a particular key within the shortcode to use that name and value accordingly. Like here:

{{ get key which equals to 'A' }}
  <h3>[get name param of that key]</h3>
  <div>[get value param of that key]</div>
{{ end }}

These names and values are translation strings which might slightly differ from page to page, but that I will take care of in the content of a page.

Appreciate any ideas!

Shortcode arguments are always scalar. You can pass a pseudo array with something like “myarray=foo|bar|baz” then split inside the shortcode template. I suppose you could do something similar to pass a single-level map, something like “mymap=key1|value1|key|value2”.

Shortcode args can be multiline using the text literal delimiter. Pass inn some JSON and use transform.Unmarshal.



{{< foo `
key: {
  name: Name,
  value: Value
` >}}

… untested, but in my head, it should work.

1 Like

I’ve been playing with unmarshal and it almost works.
In the shortcode I tried this:

{{ $data := dict }}
{{ with .Params }}
  {{ with . | transform.Unmarshal }}
    {{ $data = .}}
  {{ end }}
{{ end }}

as well as this:

{{ $data := unmarshal .Params }}

and get the same error:

execute of template failed: template: shortcodes/suite.html:4:22: executing "shortcodes/suite.html" at <transform.Unmarshal>: error calling Unmarshal: type []interface {} not supported

Here is how the shortcode looks in the template:

{{< suite `
	"keyA": {
		"name": "Key A Title",
		"value": "Key A description text"
	"keyB": {
		"name": "Key B Title",
		"value": "Key B description text even longer"

I guess, the error means that I’d need to somehow change my JSON structure? But then again the docs don’t point at any formatting limitations for unmarshal.

Enclose your json string in curly braces to get a proper json root object

   "KeyA": ...,
   "keyB": ...

To get the unnamed parameter (your json) string use

{{ .Get 0 }} or {{ index .Params 0 }}
Thats something you can unmarshall

{{ $data := .Get 0 | unmarshal }}
{{ index $data "keyB" }}

Those two tricks did it, thanks!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.