Static Assets
hpy-tool
provides built-in support for handling static assets like CSS files, JavaScript files, images, fonts, and other resources that need to be served alongside your compiled HTML pages.
Enabling Static Asset Handling
To enable this feature, you must:
- Define the
static_dir_name
setting within the[tool.hpy]
table in yourhpy.toml
file. - Ensure the directory named by
static_dir_name
exists within your configuredinput_dir
.
Example hpy.toml
enabling static assets in src/static/
:
[tool.hpy]
input_dir = "src"
output_dir = "dist"
# This line enables the feature for the directory named "static"
static_dir_name = "static"
If static_dir_name
is commented out or not present in hpy.toml
, static asset handling is disabled.
How it Works
When static asset handling is enabled:
- During Build (`hpy` or `hpy src`): The entire contents of the source static directory (
) are recursively copied into the output directory, preserving the directory structure, under the same name (/ /
). For example,/ / src/static/css/style.css
becomesdist/static/css/style.css
. The copy operation usesshutil.copytree
withdirs_exist_ok=True
, so it handles updates correctly on subsequent builds. - During Watch Mode (`hpy -w`): The watcher monitors the source static directory for changes:
- Create/Modify: When a file or directory is created or modified within the source static directory, it is copied (or updated) to the corresponding location in the output static directory.
- Delete: When a file or directory is deleted from the source static directory, the corresponding file or directory is removed from the output static directory.
- Rename/Move: Renaming or moving files/directories within the static directory is handled by deleting the old target path and copying to the new target path.
.hpy
File Exclusion: Any.hpy
files placed inside the designated static directory are ignored by the page compilation process. They are treated simply as static files and will be copied as-is.
Referencing Static Assets
When referencing static assets in your HTML (e.g., in `_layout.hpy` or page files) or CSS, use paths relative to the root of the output directory.
Since the static assets are copied into
, you typically reference them starting with /
.
Examples (assuming static_dir_name = "static"
):
- Linking a CSS file (
src/static/css/theme.css
): - Displaying an image (
src/static/images/logo.png
): - Referencing a font in CSS (
src/static/fonts/font.woff2
):@font-face { font-family: 'MyFont'; src: url('/static/fonts/font.woff2') format('woff2'); }
The development server correctly serves these files from the output directory.