PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 1, 2022

[FIXED] How do I use JS String Interpolation to insert Shopify sections? ('not a valid section type')

 July 01, 2022     javascript, liquid, shopify     No comments   

Issue

I'm building a 'view' template for certain blogs' tags. I'm grabbing the pathname with javascript and trying to insert a hero section based on which tag the user is on. If I hardcode the blog name and tag into the section string, it works. But if I try to interpolate the variables into it, I get a liquid error.

The code:

const pathName = window.location.pathname;
let blog_div = document.getElementById('blog-hero');
let blogName = pathName.split('/')[2];
let tagName = pathName.split('/')[4];

return blog_div.innerHTML = `{% section 'blog--hero-${blogName}-blog--${tagName}' %}`;

Expected Output: Section loads on screen

Actual Output: Nothing on-screen. Error in HTML: 'Liquid error: Error in tag 'section' - 'blog--hero-(blogName)-blog--(tagName)' is not a valid section type'


Solution

Ended up using the Section Rendering API, per the docs.

But the JSON.parse() line didn't work. So I had to use the onload, readyState, and status methods per the MDN docs

New code ended up looking like

const pathName = window.location.pathname;
let blog_div = document.getElementById('blog-hero');
let blogName = pathName.split('/')[2];
let tagName = pathName.split('/')[4];

let request = new XMLHttpRequest();
request.open('GET', `/?section_id=blog--hero-${blogName}-blog--${tagName}`)
request.onload = () => {
    if(request.readyState === request.DONE) {
        if (request.status === 200) {
            blog_div.innerHTML = request.responseText;
        }
    }
};

request.send(null);


Answered By - Jason
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing