In Squiz Matrix, if you’re reading an XML data source and passing a parameter to this data source that you are not sure if any data exists, you might want to send a 404 if no data is found as opposed to an empty asset returning a 200 Success. A couple of requirements are needed for this to work:
- Your XML data source to return some form of XML if no result was found
- XSL layout to render returned XML
What to do?
- Ensure that you specified an asset for your Page Not Found field in the Site asset of your site.
- Create a redirect page, note it’s asset id.
- On the details screen, set the URL field to a path that does not exist on your site.
- In your XSL, add the following Global Keyword replacement in your template that matches your error and set the asset id of the redirect we created in Step 2:
%globals_asset_contents_raw:1111%
That’s it! You’re page will now redirect to a 404 if it encounters your error XML.
XML response of a successful request for data:
<?xml version="1.0" encoding="UTF-8"?> <feed> <entry> <title>Test</title> </entry> </feed>
XML response but with no data found:
<?xml version="1.0" encoding="UTF-8"?> <error>No data found!</error>
The XSL that will process the XML response:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Render the successful results --> <xsl:template match="/feed"> <xsl:for-each select="entry"> <xsl:value-of select="title"/> </xsl:for-each> </xsl:template> <!-- Unsuccessful response --> <xsl:template match="/error"> <xsl:text>%globals_asset_contents_raw:45%</xsl:text> </xsl:template> </xsl:stylesheet>
As you will have noticed, you can embed Global / Common keywords within XSL files. This is a very powerful method to deliver content based on a number of variables. You could, in this instance, serve another XML data source if no data was found in this one or some other dynamic/static content from within Matrix.