1.0.1 • Published 6 years ago

json-pages v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

json-pages

Middleware for express that injects JSON into a html template and serves the web page on the server.

Instalation

$ npm install json-pages

Getting Started

To use the json-pages you will need to put your json files and a html template (.html suffixed) together into a folder.

Then you can use the middleware simply as:

	var jsonPages = require('json-pages')

	app.use(jsonPages(pathToFolder [, id]))

'pathToFolder' - May be the relative or absolute path to the folder where the files are contained.

'id' - optional Is the key for the JSON objects that will be used to uniquely identify each object in the URL path. If one is not specified the paths will default to a number count, starting from 0.

Caution Note: The middleware injects the data directly from the JSON file. Using with unsafe JSON files may leave your site vulnerable to XSS attacks.

Note: The HTML template must have the placeholder keys escaped with double curly braces, similar to a mustache template.

	<h1>{{title}}</h1>

JSON file format

json-pages expects the JSON files to be formatted as a list of objects.

An example of a valid JSON file:

[
	{
		"title": "Where the Crawdads Sing",
        "author": "Delia Owens",
        "cover": "http://image.com/crawdad",
	},
	{
		"title": "A Song of Ice and Fire",
		"author": "George R. R. Martin",
		"cover": "http://image.com/exampe"
	},
	...
]

Optional id argument

The id argument should be a key of an unique field in each of the objects of the list. It will serve as the path of the url of the page.

In the example above we could pass the key "title" in the middleware, then the values for "title" key would be used to generate the URLs. The templates would then be served at:

  • 'example.com/Where%20the%20Crawdads%20Sing'
  • 'example.com/A%20Song%20of%20Ice%20and%20Fire'

If the argument is not specified then the pages would be server at serialized numeric values from 0 to n. The resulting templates would be served at:

  • 'example.com/0'
  • 'example.com/1'

Example:

/index.js:

	var jsonPages = require('json-pages')

	app.use('/books', jsonPages('./booksFolder', 'id'));

/bookFolder/books.json:

[ 
    {
        "id": "CGVDDwAAQBAJ",
        "title": "Where the Crawdads Sing",
        "author": "Delia Owens",
        "cover": "http://image.com/dslfjdsklfj",
        "category": "Fiction"
    },
	{
		...
	},
	...
]

/bookFolder/book.html

	<body>
		<h1>{{title}}</h1>
		<img src={{image}} alt="..."/>
		...
	</body>

The page would be served at: '/books/CGVDDwAAQBAJ'

License

MIT