Liquid Tutorial 5 - Accessing data from the page and URL

So far we have created variables to store data manually and accessed that data, but often we want to access data that has been provided by external sources. A good place to start is looking at information about the URL and the current Page.

Written By Matt Jones

Last updated About 1 month ago

Introducing the Context Object

In this article we’ll show you how you can start to get useful information from the built-in context object and use it with your Liquid code. If you want to know more about what sort of data is available in the context object, we have a more detailed reference here: Reference - Exploring the Context Object .

Accessing Data from the Current Page

You can access information about the current page you’re working on by outputting the page Object (a property of the context object). The following example shows you what to expect, but we strongly recommend you do this on the page you’re working on so that you can see what’s available in your page. Each page will have different data.

Example
{{context.page}}

Notice there is an HTML tab which shows how the data will actually look when you output on the page. To make it easier to read, you can format it, see the Formatted JSON tab. To re-cap how to do this to your data, see: Liquid Tutorial 3 - Creating Liquid objects and accessing their properties

This Object shows you information which is also available if you use Siteglide CLI to pull the site and inspect the page file. However, in the file structure in CLI, this information will be displayed in YML format rather than JSON. See Pages with Siteglide CLI

The metadata object can be modified in Siteglide CLI too, but it’s also possible to modify it in Siteglide Admin. For example, it contains some properties which can be modified under the SEO tab in Siteglide CMS/pages and also contains the values of custom page fields. See:

The Anatomy of a URL

Let’s take an example URL and break it down into its constituent parts. Once you understand the job of each part of the URL, you can start to understand how you can use the URL to load different versions of the same page by sending information to the page and reading it with Liquid.

https://siteglide.featurebase.app/en/help/articles/5602274-liquid-tutorial-5-accessing-data-from-the-page-url?search=needle&sort=acsending#theAnatomyOfAURL

Our main source for this section was https://www.geeksforgeeks.org/computer-networks/components-of-a-url/ - feel free to check it out!

Name of URL component

Purpose

Example

Request Headers, Cookies and Method

Not actually part of the URL and not visible in it, but useful to know about. Information sent by the browser to the server indicating contextual information like IP address, device type and referring URL. Cookies tell visitor information and Method explains whether the URL will GET a document or carry out some other kind of action e.g. a Form Submission.

Protocol

Tells the browser what kind of security and other rules to follow for the URL.

https://

Subdomain

Allows websites to have an area of the site with a distinct identity.

siteglide

Domain Name

The main purchased domain which allows a site to be identified.

featurebase

Top-level Domain

indicates the type of organization the website is registered to

.com

Path

In the old days, this was literally where to find the HTML file for the page in the folder structure, including the file name and extension.

These days, it’s possible that the real file path isn’t exactly the same as the path, but the important thing is that it’s a unique reference the server can use to find the page.

/en/help/articles/5602274-liquid-tutorial-5-accessing-data-from-the-page-url

Query String Separator

Indicates the end of the path, if a query string follows

?

Query String

Any optional parameters sent to the page

search=needle&sort=acsending

Fragment

Used for deep-linking this component indicates the ID of an HTML element which should be scrolled to the top of the page when it loads.

#theAnatomyOfAURL

In Siteglide, most of this information is accessed via the location property of the context object. The first step is usually to output this, and analyse it to see which properties you need:

Example
{{context.location}}

In this previous article, we explain how you can format the JSON output to read it more clearly: Liquid Tutorial 3 - Creating Liquid objects and accessing their properties . You can also get a useful breakdown of the path using the params property Object:

Example
{{context.params}}

You can also access further useful information about the request headers:

Example
{{context.headers}}

Below is a full table of example properties you can fetch (however, we’d strongly recommend you output the real object for your page and explore as suggested above). Note some rows do not have a specific property where you can fetch that data; if so it’s probably because it’s less commonly needed. If you do need it, it can be derived from the main URL using filters.

Name of URL component

Example

Liquid Output Code

full URL

https://mj-siteglide-fb-studio-copy.staging-siteglide.com/learning-about-urls/anatomy-of-a-url?search=needle\u0026order=asc

{{context.location.url}}

Host / Origin - A combination of subdomain, host name and top level domain.

mj-siteglide-fb-studio-copy.staging-siteglide.com

{{context.location.host}}

Path

/learning-about-urls/anatomy-of-a-url

Get the full path:{{context.location.pathname}}

Or access individual “slugs” within the path:

{{context.params.slug}}
{{context.params.slug2}}
{{context.params.slug3}}

Any further slugs after that must be derived from:

{{context.params.slugs}} 

e.g.

{% assign slugs = context.params.slugs | split: “/” %}{% assign slug4 = slugs[0] %}{% assign slug5 = slugs[1] %}
{{slug4}}

Query String / Search

?search=needle&order=asc

Access each search parameter individually - the search object will automatically be given properties for each available search parameter:

{{context.location.search.search}}
{{context.location.search.order}}

Fragment

#accessingTheCurrentURL

Derive from context.location.href e.g.

{% assign split_fragment = context.location.href | split: “#” %}
{% assign fragment = split_fragment[1] %}
{{ fragment }}

Post data

If the request was sent with the method POST, additional information will be available here as a string- it can be parsed by JSON in order to make its properties accessible.

Depending on the response headers being set, this may also appear in context.params, but by default it will not be.

{% assign data = context.post_params | parse_json %}
{{data}}

Sending information in Query Parameters - by Navigating to a URL

If you’re familiar with HTML, you probably already know the simplest way to navigate to a URL is to create an anchor element with the desired URL in the href attribute. By changing the URL to include query parameters, we can send the information to the page that we want it to search for a “needle”:

Example
<a href="/learning-about-urls/anatomy-of-a-url?keyword=needle\u0026order=asc">Search for a needle</a>

When the page loads, we can output the information which was sent to the page using Liquid:

Example
You are searching for the search terms: {{context.location.search.keyword}}

Security note: Normally, outputting information from the URL on the page can be a security risk known as XSS or Cross-site Scripting. This is because a malicious person can give someone a link to your site which when output on the page as HTML is able to run malicious JavaScript- directly from the instructions in the URL. e.g.

https://example.com/search?keyword=<script>alert('evil code!')</script>

Siteglide has built in default protections to defend against this kind of attack (using sanitization to convert dangerous strings to something which will not evaluate on the browser), so it is safe to output this information (unless you use something like the html_safe filter to turn this protection off for a specific output (not recommended except in specific situations with trusted sources of data)).

A link is all very well on its own, but it doesn’t give the user much choice about what information they are looking for; for this, a form is more useful:

Example
<form action="/learning-about-urls/anatomy-of-a-url" method="GET"> <input type="text" name="keyword" placeholder="Enter search terms"> <input type="hidden" name="sort" value="asc"> <input type="submit" value="submit"> </form>
  1. The action is the URL of the Page we want to send the information to.

  2. The method is GET - it will carry out a normal re-load of the page when the form is submitted and use the URL to store data.

  3. Query parameters are created based on the name of the input and its value.

Submitting the form will re-load the page. To make the form more re-usable, instead of hard-coding the action, we can actually make sure it reloads the current page by dynamically inserting the current page’s path:

Example
<form action="{{context.location.pathname}}" method="GET"> <input type="text" name="keyword" placeholder="Enter search terms"> <input type="hidden" name="sort" value="asc"> <input type="submit" value="submit"> </form>

It would be incorrect to use the context.location.href or context.location.url here. Both contain more than just the path alone- we don’t want any existing query parameters to be preserved, but to set new ones.

Activity - A Simple Calculator

You now have all the building blocks you need to allow a website user to send information to a page via the URL and for Liquid to use it and calculate what kind of response to give.

For the next activity, try and create a simple calculator which only carries out a single operation e.g. multiplication:

  1. Create a new Page in Siteglide and give it a non-Studio Page Template

  2. Create a form like the one above to allow the user to enter the two numbers they wish to multiply.

  3. Use Liquid to read the URL query String and store variables

  4. Use Liquid to filter the variables and output the answer to the page

  5. Access the page’s meta_title and use it to create a heading above your calculator. You can set the data for the title in the SEO tab in Siteglide.

Whenever you are in need of a new filter which has not yet been covered by these tutorials or you don’t remember, hit the reference docs on platformOS:

Note, you may find the calculator errors on the page before the user has added any numbers. That’s okay for now, in the next tutorial we’ll look at logic which can decide not to carry out a calculation until certain conditions have been met.