The subpage tag within NationBuilder is really useful in allowing you to take content from one page on your site and add it to another. For instance, you might want to insert a subpage that shows your latest three blog posts or something like that.
However, if for any reason the, page being referenced in the subpage tag no longer exists (maybe it’s accidentally been deleted or is no longer relevant) then you will get a publicly visible liquid retro message that reads something like this…
Liquid syntax error: Error in tag ‘subpage’ – No such page slug ‘your_missing_page’
I wanted to find a way to check if the subpage exists at all and if not, nothing should appear.
My first thought was to check the page slug against an array of all the published pages on the site to see if there was a match. Should be easy enough right? Except no, as far as I can tell there is no way to return an array of ALL the published pages. You can return the 20 most recent pages within most page types but that leaves too much room for error on a large site. You could also return any nav pages with all the children underneath them. Almost good, but not for pages that are neither nav pages nor children of nav pages, which is entirely plausible. Looks like my array check method was a non starter.
Finally I got lucky and stumbled across a post on Stack Overflow (//stackoverflow.com/questions/14667270/shopify-liquid-how-can-i-conditionally-include-snippets-in-shopify-liquid) which uses the liquid capture tag to check if an include file exists. The method was easily applicable to the subpage tag and works like this…
Firstly, “capture” the returned subpage content as a variable using the capture tag…
{% capture my_subpage_content %} {% subpage 'blog' with 'latest_blog_posts’' %} {% endcapture %}
Here we are creating a variable ‘my_subpage_content’ which contains anything returned from the subpage tag contained within the capture tag (in this instance we’re trying to find a page called blog and we’re going to use a template called latest_blog_posts to display content from it).
Secondly, check to see if the variable returned contains a Liquid syntax error…
{% capture my_subpage_content %} {% subpage 'blog' with 'latest_blog_posts’' %} {% endcapture %}
{% unless my_subpage_content contains "Liquid syntax error" %} {{my_subpage_content}} {% endunless %}
Here we’re outputting the variable we just created but we’re wrapping it in an unless tag which is checking to see if our variable contains the words ‘Liquid syntax error’. Our subpage content will be output through our variable UNLESS the variable contains the words ‘Liquid syntax error’, in which case nothing will appear.
Leave a Reply