kanva.js is a lightweight JavaScript library designed to simplify the process of loading and rendering HTML partials within your web applications. It provides an easy way to manage and include reusable components, improving maintainability and modularity.
- Dynamic loading of HTML partials based on URL or custom attributes.
- Easy integration with existing projects.
- Lightweight and fast, without dependencies.
You can include kanva.js
in your project by downloading the file or linking to it via a CDN.
<script src="path/to/kanva.js"></script>
Ensure that your HTML structure includes a element where the content will be dynamically loaded.
Your HTML should contain a <template-hook>
element, which can be configured to load different partials based on attributes. You can use kanva.js
in several ways:
1. By Name: Load a specific partial by setting the name
attribute on the <template-hook>
.
<template-hook name="about"></template-hook>
This will load the about.tpl
partial from the _partials/
directory.
2. By Route: Load a partial based on the current URL. Set the route
attribute on the <template-hook>
.
<template-hook route></template-hook>
This will load a partial matching the last segment of the URL (e.g., /home
loads home.tpl
).
3. With Dynamic Data: Inject dynamic data into your partial using the data
attribute (must be valid JSON). Use {{key}}
in your partial to reference data keys.
<template-hook name="about" data='{"username": "Alice"}'></template-hook>
If about.tpl
contains Hello, {{username}}!
, it will render as Hello, Alice!
.
4. SPA Navigation: For single-page app navigation, use anchor tags with the data-kanva-link
attribute. Clicking these links updates the URL and reloads partials without a full page refresh.
<a href="/about" data-kanva-link>About</a>
Error Handling:
- If a partial is missing, a red error message is shown in the hook.
- If neither
name
norroute
is specified, a red error message is shown.
No Initialization Needed:
kanva.js
auto-initializes onDOMContentLoaded
. No manual setup is required.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>kanva.js Example</title>
<script src="path/to/kanva.js" defer></script>
</head>
<body>
<nav>
<a href="/home" data-kanva-link>Home</a>
<a href="/about" data-kanva-link>About</a>
</nav>
<template-hook route></template-hook>
<template-hook name="about" data='{"username": "Alice"}'></template-hook>
</body>
</html>
I welcome contributions! To get involved, please fork the repository and submit a pull request. For significant changes, consider opening an issue first to discuss your ideas.
This project is licensed under the MIT License. See the LICENSE file for details.