All Projects → nicojs → typed-html

nicojs / typed-html

Licence: other
TypeSafe HTML templates using TypeScript. No need to learn a template library.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to typed-html

simple-template
Text templating processor for SWI-Prolog.
Stars: ✭ 29 (-68.48%)
Mutual labels:  template-engine
pug4py
Use Pug.js within any python framework
Stars: ✭ 17 (-81.52%)
Mutual labels:  template-engine
Giraffe.Razor
Razor view engine http handlers for Giraffe web applications.
Stars: ✭ 27 (-70.65%)
Mutual labels:  template-engine
hydrate-text
A small, dependency-free and strongly typed template engine.
Stars: ✭ 45 (-51.09%)
Mutual labels:  template-engine
laravel-theme
This package creates multiple managed theme infrastructure for Laravel.
Stars: ✭ 19 (-79.35%)
Mutual labels:  template-engine
papercraft
Composable templating for Ruby
Stars: ✭ 162 (+76.09%)
Mutual labels:  template-engine
bash-tpl
A smart, lightweight shell script templating engine, written in Bash
Stars: ✭ 26 (-71.74%)
Mutual labels:  template-engine
gktemplate
GKTemplate - 采用Go开发的DedeCMS模板解析器
Stars: ✭ 32 (-65.22%)
Mutual labels:  template-engine
Magento2-Twig
Twig Template Engine for Magento2
Stars: ✭ 58 (-36.96%)
Mutual labels:  template-engine
liquidpy
A port of liquid template engine for python
Stars: ✭ 49 (-46.74%)
Mutual labels:  template-engine
mole
A tool for managing design decision outputs for different platforms
Stars: ✭ 30 (-67.39%)
Mutual labels:  template-engine
cinje
A Pythonic and ultra fast template engine DSL.
Stars: ✭ 26 (-71.74%)
Mutual labels:  template-engine
nhplate
Net Heroes Template Engine for Node.js and browsers
Stars: ✭ 26 (-71.74%)
Mutual labels:  template-engine
Textrude
Code generation from YAML/JSON/CSV models via SCRIBAN templates
Stars: ✭ 79 (-14.13%)
Mutual labels:  template-engine
Glize
📚 Glize is a clean and robust pure Javascript library.
Stars: ✭ 16 (-82.61%)
Mutual labels:  template-engine
TemplateEngine
Design and build web applications with components using only your web browser
Stars: ✭ 41 (-55.43%)
Mutual labels:  template-engine
cheetah3
Cheetah3 is a free (MIT) and open source template engine for Python.
Stars: ✭ 106 (+15.22%)
Mutual labels:  template-engine
nunjucks-loader
Webpack loader for Nunjucks templates
Stars: ✭ 20 (-78.26%)
Mutual labels:  template-engine
voldemort
A simple static site generator using Jinja2 and Markdown templates.
Stars: ✭ 48 (-47.83%)
Mutual labels:  template-engine
LiquidKit
Liquid template language parser engine in Swift.
Stars: ✭ 19 (-79.35%)
Mutual labels:  template-engine

Build Status

Typed HTML

HTML templates have never been this easy. Type safe using plain TypeScript with a minimal runtime footprint. No need to learn a template language, if you know TypeScript, you're set.

This:

// example.tsx
const item = 'item';
const icon = 'icon-add';
const ul = <ul>
    <li>{item}</li>
</ul>;

typeof ul; // string

const button = <button onclick="handleClick">
    <i class={icon}></i>
</button>;

typeof button; // string

console.log(ul);
console.log(button);

Prints:

<ul>
    <li>item</li>
</ul>
<button onclick="handleClick">
    <i class="icon-add"></i>
</button>

Getting started

Install:

npm install --save typed-html

Configure your TypeScript compiler for JSX:

{
    "compilerOptions": {
        "jsx": "react",
        "jsxFactory": "elements.createElement"
    }
}

Although we're configuring the compiler to use React, this is not what is being used. Instead, we redirect all jsx element to typed-html's elements.createElement.

Now create a *.tsx file. For example: example.tsx with the following content:

// example.tsx
import * as elements from 'typed-html';

const w = 'world';
const helloWorld = <p>Hello <strong>{w}</strong></p>;

typeof helloWorld; // => Just a string of course

However, the following piece of code will NOT compile:

<foo></foo>; // => Error: Property 'foo' does not exist on type 'JSX.IntrinsicElements'.
<a foo="bar"></a>; // => Error:  Property 'foo' does not exist on type 'HtmlAnchorTag'

Supported environments

Typed HTML supports both NodeJS and (since 2.0) the browser.

For use in the browser, either load typed-html as a module, or use a bundler like webpack or rollup to bundle the package for you.

// Direct ES import:
import * as elements from './node_modules/typed-html/dist/elements.js';
// OR, when using a bundler like rollup or webpack
import * as elements from 'typed-html';

Supported scenarios

All template scenarios are supported with plain TypeScript.

Control flow

Conditional template with ?

<div>Random > 0.5: {Math.random() > .5 ? <strong>yes</strong> : 'no'}</div>

Repeat a template with Array.map

const items = ['item', 'item2'];
<ul>
    {items.map(i => <li>{i}</li>)}
</ul>;

Helper templates

Want a helper template? Just call a function

function listItem(n: number) {
    return <li>{n}</li>;
}
<ul>
    {[1, 2].map(listItem)}
</ul>

Using a helper template like an element

Want a helper component? Create a function that implements CustomElementHandler and you can call it like an HTML element.

import {Attributes, CustomElementHandler} from "typed-html"

function Button(attributes: Attributes | undefined, contents: string[]) {
    return <div><button type="button" class="original-class" {...attributes}>{contents}</button></div>;
}
// Or 
const Button: CustomElementHandler = (attributes, contents) => <div><button type="button" class="original-class" {...attributes}>{contents}</button></div>;
}
    
console.log(<Button style="color:#f00">Button Text</Button>);

Prints:

<div>
    <button type="button" class="original-class" style="color:#f00">Button Text</button>
</div>

React-style children

It's possible to write React-style components as well. Consider the example below.

import {Attributes, CustomElementHandler} from "typed-html"

function Button({ children, ...attributes }: Attributes) {
    return <div><button type="button" class="original-class" {...attributes}>{children}</button></div>;
}

console.log(<Button style="color:#f00">Button Text</Button>);

Prints:

<div>
    <button type="button" class="original-class" style="color:#f00">Button Text</button>
</div>

Sanitization

Security is NOT a feature. This library does NOT sanitize.

const script = '<script>alert("hacked!")</script>';
const body = <body>{script}</body>;

Will result in:

<body><script>alert('hacked!');</script></body>

If you need sanitization, you can use something like sanitize-html.

Supported HTML

All HTML elements and attributes are supported, except for the svg.

Missing an element or attribute? Please create an issue or a PR to add it. It's easy to add.

Void elements

Void elements (elements without closing tags) are supported, however you should close them in TypeScript.

const img = <img href="/foo/bar.png">; // => Error! JSX element 'img' has no corresponding closing tag.

In the example above, closing the image tag is required for valid TSX code:

const img = <img href="/foo/bar.png"></img>; // => '<img href="https://github.com/foo/bar.png">'

See this code for a list of supported void elements.

Attribute types

All HTML attributes support a string value, however some attributes also support a number, Date or boolean(or absent value) type:

<meter value={1} min={0} max={5} low={1} high={4} optimum={3}></meter>; 
// => <meter value="1" min="0" max="5" low="1" high="4" optimum="3"></meter>
<ol start={3}></ol>;
<progress value={3} max={4}></progress>;
<td colspan={3} rowspan={3}></td>;
<th colspan={3} rowspan={3}></th>;

const date = new Date('1914-12-20T08:00');
<time datetime={date}></time>; 
// => <time datetime="1914-12-20T08:00:00.000Z"></time>
<ins datetime={date}>updated</ins>;
<del datetime={date}>old</del>;

// => <form> <input type="checkbox" checked> </form>
<form novalidate={false}> 
    <input type="checkbox" checked disabled={false}></input>
</form>

Custom elements

You can add custom elements by adding them to the intrinsic elements yourself:

// MyCustomElements.d.ts

declare namespace JSX {
    interface CustomElement {
        customAttribute?: string;
    }
    interface IntrinsicElements {
        myCustomElement: CustomElement;
    }
}

Now you can use it:

// UseCustomElement.ts
import * as elements from 'typed-html';

const myElement = <myCustomElement customAttribute="customValue"></myCustomElement>
console.log(myElement);

This prints:

<my-custom-element custom-attribute="customValue"></my-custom-element>

Custom attributes

Custom attribute names are already supported out-of-the-box for attributes with a dash (-) in the name. For example:

<button data-menu-item="3"></button>

Transformation

As a browser is case insensitive when it comes to element and attribute names, it is common practice to use kebab case for this. However <custom-element></custom-element> is not allowed in TypeScript. Therefore typed-html will transform <customElement></customElement> to <custom-element></custom-element>.

This transformation also works for custom attributes you define on a custom element yourself. For example:

<customElement aCustomAttr="value"></customElement>

Becomes

<custom-element a-custom-attr="value"></custom-element>

How this all works

The way this works is by using TypeScript's jsx support, but not for jsx/react interoperability. Instead, it defines the normal html tags as IntrinsicElements in the JSX namespace.

At runtime, the elements.createElement function is called for every html tag. It simply converts the given element to a string with minimal overhead.

This:

<ol start={2}>{[1, 2].map(i => <li>{i}</li>)}</ol>

Compiles to:

elements.createElement("ol", { start: 2 }, [1, 2].map(function (li) { 
    return elements.createElement("li", null, li); 
}));

Which translates to:

<ol start="2">
    <li>1</li>
    <li>2</li>
</ol>
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].