christianzoppi / storyblok-11ty

Import data from Storyblok to Eleventy (11ty)
19 stars 7 forks source link

Output from sb_blocks is treated as a string and not as html #3

Open tomAtcocreate opened 3 years ago

tomAtcocreate commented 3 years ago

Hi, I just dropped this into my 11ty solution and tried to get sb_blocks to work.

Path is fine, it finds and renders the blocks using

{% sb_blocks sida.data.bloks %}

But the output is treated as unsafe html so all tags are just outputted to screen.

I tried the | safe filter, but that did not work.

Any ideas? I'm not sure if this problem comes from nunjucks, eleventy or this plugin.

tomAtcocreate commented 3 years ago

I solved it by this change in nunjucks.js

let html_output = ''
    blocks.forEach(block => {
      block.component = utils.slugify(block.component)
      engine.opts.autoescape = false;
      let html = engine.render(`${this.blocks_folder + block.component}.njk`, { block: block })
      engine.opts.autoescape = true;
      html_output += html
    })

Turning off autoescape lets the renderer output unescaped html. I have no idea if this is the "correct" approach to solve this problem though :)

rileymacisaac commented 2 years ago

@invatom the solution you provided doesn't actually work for me for whatever reason.

I found a way to do it that might be better, but i'm not certain.

this.config.addNunjucksTag('sb_blocks', (nunjucks, nunjucksEnv) => {
      let self = this;

      return new (function () {
        this.tags = ['sb_blocks'];

        this.parse = function (parser, nodes, lexer) {
          let tok = parser.nextToken();

          let args = parser.parseSignature(null, true);
          parser.advanceAfterBlockEnd(tok.value);

          return new nodes.CallExtensionAsync(this, 'run', args);
        };

        this.run = function (context, blocks, callback) {
          let html_output = new nunjucks.runtime.SafeString(
            self.outputBlocks(blocks, nunjucksEnv)
          );
          // let html_output = self.outputBlocks(blocks, nunjucksEnv);
          return callback(null, html_output);
        };
      })();
    });

In the above, you can see I changed nunjucksEngine to just nunjucks, and then I switched let html_output ... to use SafeString (mentioned here in autoescape docs, and here in custom tags docs):

let html_output = new nunjucks.runtime.SafeString(
            self.outputBlocks(blocks, nunjucksEnv)
          );