Using Static Assets on Your Pages
This guide will help you use static assets (e.g. CSS, Javascript, or HTML files) on your pages.
Requirements
To follow the steps in this tutorial, you should be familiar with the required directory structure for your codebase, and understand the concepts of pages, layouts, and assets. You'll extend code samples from the previous tutorials.
- Directory Structure
- Pages
- Layouts
- Assets
- Reusing Code Across Multiple Pages (previous tutorial)
Steps
Note
Below steps are using Liquid filters, to learn about Liquid filters click here.
Using static assets on your pages is a four-step process:
Step 1: Create assets directory and subdirectories
If you are starting from scratch (without having created the codebase), create an assets directory inside app.
If you have already created the codebase, you can skip this step, and just locate your app/assets directory.
Create subdirectories for different assets inside the assets directory: for this tutorial, create scripts for storing Javascript files, and styles for storing CSS files.
Step 2: Create assets
Create a couple of assets.
Create a CSS file app.css in the styles directory:
body {
background-color: #ccc;
}
Create a Javascript file app.js in the scripts directory:
console.log("Hello from JS!");
Create an HTML file test.html in the assets directory:
Hello from test.html
Step 3: Check assets
Use {{ asset_url }} variable to check your assets. This will list the full URL of your assets on our content delivery network, including the time of the latest update (used for caching).
Example for this documentation site:
AssetUrlDrop
Step 4: Access assets
To access assets, use the asset_url filter in your liquid file, e.g. layout:
<html>
<head>
<link rel="stylesheet" href="{{ 'styles/app.css' | asset_url }}">
<script src="{{ 'scripts/app.js' | asset_url }}"></script>
</head>
<body>
<a href="{{ 'test.html' | asset_url }}">Test</a>
{{ content_for_layout }}
</body>
</html>
Sync or deploy. The background color of the page has changed to the color specified in the app.css file, and the link to test.html works. If you check the developer console, the Javascript is there.
Next steps
Congratulations! You have learned how to use static assets on your pages. Now you can learn about adding visuals to your pages using CSS or Javascript.