by Before Semicolon

Custom tags

A custom tag can be a class or a function which can optionally contain or return a render function.

This render function must return an HTML string, a node or null

The below search field class will be used as search-field tag. That means that how you name your class and function is how the tag name will be called.

class SearchField {
	render() {
		return `
			<label class="search-field" aria-label="search field">
				<input type="search" name="search" placeholder="Search...">
			</label>
		`;
	}
}

The same tag class can also be written as a function like so:

function SearchField {
	return () => `
		<label class="search-field" aria-label="search field">
			<input type="search" name="search" placeholder="Search...">
		</label>
	`;
}

Register your tag

After, it must be registered by passing it to the engine on start.

const {engine} = require('@beforesemicolon/html-plus');
const {SearchField} = require('./SearchField.js');

const app = express();

engine(app, path.resolve(__dirname, './pages'), {
	customTags: [SearchField]
});

Use your tag

We can now use it in our template as so:

<search-field></search-field>

Working with Attributes

The custom tag is initialized with two arguments. The Element object and the options the node was created with.

To accept a value and placeholder attribute we can use a constructor to collect the node.

const {html} = require('@beforesemicolon/html-plus');

class SearchField {
	constructor(node, options) {
		this.node = node;
	}

	render() {
		return html(`
			<label class="search-field" aria-label="search field">
				<input type="search" name="search" placeholder="{placeholder}" value="{value}">
			</label>
		`, {
			value: this.node.getAttribute('value'),
			placeholder: this.node.getAttribute('placeholder') || 'Search...',
		});
	}
}

Now we can pass value and placeholder to our tag like normal HTML.

<search-field value="sample" placeholder="Find..."></search-field>

The node object will contain things like the attributes object and methods like getAttribute and setAttribute that you can use.

Note: custom tags are SSR. This means that only the HTML returned by the render method will be shipped to the browsers.