0.0.1 • Published 2 years ago

stached v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Stache

Module for creating Handlebars components easily with Express.

Getting Started

Create an Express server

First, you need to create an Express server, make sure to pass in the stached function as a prop when rendering your index (we'll call it 'components')

// server.js
const express = require('express');
const app = express();

const getComponentsFromDir = require('stached');

app.use(express.static('public'));
app.set('view engine', 'hbs');

app.get('/', (req, res) => {
    res.render('index', {components: getComponentsFromDir('./views/components')});
});

app.listen(process.env.PORT || 3000, e => {
    if(e) console.error(e);
    else console.log('Running!');
});

Create a component file

Now, create a .hbs file with your component. Wrap everything you'll be using for the component in a div with a unique ID. You can add a stylesheet to your component by using Stache.addLocalStyle(div_id, stylesheet_path). Note: Your stylesheet path must begin with a '/'. When using this method you must also have a <head> tag in the file you will be using the component.

<!-- views/components/myComponent.hbs -->
<div id="myComponent">
    <p>Hello!</p>
</div>
<script>
    Stache.addLocalStyle("myComponent", "/myComponent.css");
</script>

Create your stylesheet

This step is simple, just create a stylesheet with whatever styles you choose. Note: DO NOT make things here come after the id of your component if you will be adding it using the addLocalStyle(...) method: it will add '#myComponent' (or whatever your ID is) automatically.

/* public/myComponent.css */
p {
    color: red;
}

Create an index file

Now create your index file, the import for the frontend methods that wwill be used in components can be found below. Make sure that if you are going to import this you do it somewhere before the component is loaded.

<!-- views/index.hbs -->
<!DOCTYPE html>
<html>
    <head>
        <title>My App</title>
        <script src="https://raw.githubusercontent.com/sqwyer/stached/main/static/stache.min.js"></script>
    </head>
    <body>
        <p>Welcome to my app!</p>
        {{{components.myComponent}}}
    </body>
</html>

Start your server

Now start your server and it should work smoothly!

Important

  1. Script import URL: <script src="https://raw.githubusercontent.com/sqwyer/stached/main/static/stache.min.js"></script>