als-layout v6.1.0
als-layout Documentation
als-layout
is a JavaScript library designed to simplify and enhance the process of constructing and managing web page layouts. It provides a comprehensive API for modifying HTML documents dynamically, allowing developers to add, update, and manipulate various elements such as meta tags, styles, scripts, and more.
The als-layout
library is versatile, suitable for:
- Building dynamic web pages that require frequent updates to their metadata, styles, or scripts.
- Creating templating systems where multiple page layouts share similar structures but differ in content or styling.
- Developing web applications that need to dynamically adjust their UI based on user interactions or data changes.
Installation and Adding
To use the als-layout
library in your project, you can install it via npm and then include it in your JavaScript files:
npm i als-layout
const Layout = require('als-layout')
Change Log for V6
The code refactored.
Removed
- no deepclone for options, using { ...Layout.options, ...options } instead
- no onload method
Added
- status
- end(res)
Basic Usage
Initialization
To start using als-layout
, you first need to create a new instance of Layout
. This instance will serve as the foundation for building and modifying your web page.
const Layout = require('als-layout');
const layout = new Layout();
Adding Different Elements
Once you have your Layout
instance, you can easily add or modify various elements of your web page. Here are some examples of how you can use the library to customize your layout:
const layout = new Layout()
.viewport() // default width=device-width, initial-scale=1.0
.title('Test title') // adding/updating title and meta[og:title]
.favicon('/favicon.png') // adding/updating link[rel=icon][type=image/x-icon] with new href
.keywords(['some', 'keyword']) // adding/updating meta[name=keywords]. not adding existing keywords
.image('/main-image.png', '1.5') // adding/updating meta - og:image, twitter:image, twitter:card
.description('Cool site') // adding/updating meta og:description, twitter:description, and description tag
.url('/some', 'http://site.com') // adding/updating meta[og:url] and link[rel="canonical"]
.style('body {margin:0; background-color:whitesmoke;}', true) // adding css styles to existing/new style tag. Second parameter is minified (default=false).
.link('/styles.css') // adding link[rel=stylesheet] if such href not exists
.script({src:'/app.js'}, '', true) // set script with src to head if such src not exists
.script({}, 'console.log("hello world")', false) // set script with script code to footer
// Accessors for document parts
layout.body // getter for body element (if not exists, created)
layout.head // getter for head element (if not exists, created)
layout.html // getter for html Element (if not exists, created)
// Outputs
layout.rawHtml // raw HTML of the document
layout.clone // creates a new layout object clone for current object
Cloning Functionality
What is Cloning and Why is it Necessary?
Cloning in the als-layout
library refers to creating a complete, independent copy of the existing Layout
instance. This functionality is crucial when you need to generate multiple pages or versions of a page from a single base layout without affecting the original setup.
How to Use Cloning
To clone a Layout
instance, simply use the clone
method. This method creates a new Layout
instance with the same properties and settings as the original, allowing for independent modifications without interference.
const newLayout = layout.clone;
Benefits of Cloning
- Efficiency: Cloning is highly efficient, especially for creating pages with similar structures but different content or styles. It avoids the overhead of reinitializing and reconfiguring a new
Layout
instance from scratch. - Speed: Cloning is fast, typically taking less than 20ms even for large pages. This makes it ideal for high-performance web applications that need to dynamically generate content.
- Isolation: Changes made to a cloned
Layout
do not affect the original, ensuring that each instance can be modified independently based on specific requirements.
Cloning is particularly useful in scenarios where templates or base layouts are used repeatedly with slight variations, providing a robust and scalable solution for web page generation.
propsToClone
You can add properties to add when cloning the object, by adding name of properties to Layout.propsToClone
which is array.
Example:
Layout.propsToClone.push('projectName')
const layout = new Layout()
layout.projectName = 'Cool project'
const cloned = layout.clone
console.log(cloned.projectName) // 'Cool project'
Advanced Usage
The als-layout
library allows for sophisticated manipulation of web page layouts, providing robust tools for creating dynamic and complex web pages. Below is an advanced example demonstrating various capabilities of the library:
const Layout = require('als-layout')
// Starting with a basic HTML template and specifying the host for URL methods
const raw = /*html*/`<html></html>`
const host = 'http://example.com';
const options = {
logger,
host,
minified=false
}
const layout = new Layout(raw, options).lang('fr')
console.log(layout.rawHtml)
// <!DOCTYPE html><html lang="fr"><head></p></head><body></body></html>
// Cloning the initial layout to create a specialized page
const homePage = layout.clone
homeAutoReload = layout.clone
homePage.title('Home page')
homePage.body.innerHTML = /*html*/`<h1>Home page</h1>`
console.log(homePage.rawHtml)
// <!DOCTYPE html><html lang="fr"><head><title>Home page</title><meta property="og:title" content="Home page"></head><body><h1>Home page</h1></body></html>
// Adding script that reloads the page every minute
homeAutoReload.script({}, 'setTimeout(function() { window.location.reload(); }, 60000);', false)
console.log(homeAutoReload.rawHtml)
// <!DOCTYPE html><html lang="fr"><head><title>Automatic Reload Page</title><meta property="og:title" content="Automatic Reload Page"></head><body><script>setTimeout(function() { window.location.reload(); }, 60000);</script></body></html>
// Demonstrating dynamic stylesheet linkage with versioning
homePage.link('/css/main.css')
console.log(homePage.rawHtml)
// Includes link to the stylesheet with version parameter to ensure fresh cache
In this example:
- We start with a basic HTML template and use the
lang
method to set the language. - We use the
clone
method to create two versions of the base layout: one for the home page and another that automatically reloads every minute. - We manipulate the
body
of thehomePage
to include custom HTML. - We add a script to
homeAutoReload
that sets up an automatic page reload, showcasing how to insert JavaScript dynamically. - We dynamically add a versioned link to a stylesheet in the
homePage
, demonstrating control over caching and resource management.
This advanced example illustrates how als-layout
can be used to handle complex scenarios and requirements in web development, enhancing the flexibility and power at your disposal.
Response with status
In version 6, added two methods:
1. status(statusCode)
- adds the statusCode to __status
property
2. end(res)
1. writes head with __status, { 'Content-Type': 'text/html' }
2. runs res.end(this.rawHtml)
The main idea, is to add quick way to response with layout.
API
Constructor
new Layout(html: string, options: object)
Creates a new Layout
instance.
- html: The initial HTML document string.
- options: Configuration options for the layout instance.
- minified: Boolean (default:
false
). Determines if inline CSS and JavaScript should be minified. - logger: Function (default:
console
). Function for errors in minifiying and url method. - host: String (defult:
undefined
). String for url method.
- minified: Boolean (default:
Properties
layout.rawHtml
Returns the inner HTML of the document.
layout.clone
Creates a clone of the current layout instance, preserving options
.
__status
Stores the statusCode for end
method.
Methods
lang(lang: string): this
Sets the lang
attribute on the <html>
element.
title(title: string): this
Sets the document title and creates an Open Graph title meta tag.
description(description: string): this
Adds description meta tags for SEO and social platforms.
favicon(href: string): this
Sets or updates the favicon URL.
meta(props: object): this
Adds or updates a <meta>
tag with specified attributes.
- props: An object where each key-value pair corresponds to a meta attribute.
keywords(keywords: array): this
Sets or appends keywords in the content
attribute of a <meta name="keywords">
tag.
viewport(viewport: string): this
Sets the viewport meta tag. Default: width=device-width, initial-scale=1.0
.
image(image: string): this
Sets meta tags for Open Graph and Twitter cards for an image.
style(styles: string, minified: boolean = this.options.minified): this
Adds inline CSS to the document. If minified
is true, the CSS is minified.
- styles: CSS string.
- minified: Boolean (optional).
url(url: string, host: string = this.URL): this
Sets the canonical URL and Open Graph URL meta tags.
script(attrs: object = {}, innerHTML: string = '', head: boolean = true, minified: boolean = this.options.minified): this
Adds a <script>
tag to the document.
- attrs: Attributes for the
<script>
tag. - innerHTML: Inline JavaScript (optional).
- head: Boolean (default:
true
). Iffalse
, the script is added to<body>
. - minified: Boolean. If true, inline JavaScript is minified.
link(href: string, attributes: object = { rel: "stylesheet", type: "text/css" }): this
Adds a <link>
tag for external stylesheets.
status(statusCode:number): this
Adds the statusCode to __status
property
end(res):undefined
Response with res(rawHtml)
6 months ago
6 months ago
7 months ago
8 months ago
8 months ago
8 months ago
8 months ago
10 months ago
10 months ago
9 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago