What is url-template?
The url-template npm package is a utility for expanding URLs that follow the URI Template specification as per RFC 6570. This package allows developers to programmatically build URLs with variable substitutions in a template format, making it easier to handle complex URL generation scenarios.
What are url-template's main functionalities?
URL Expansion
This feature allows for the expansion of URL templates with variables. The template is defined with placeholders, and the expand method replaces these placeholders with actual values provided in an object.
var urlTemplate = require('url-template');
var template = urlTemplate.parse('/{section}/{topic}{?orderby,direction}');
var url = template.expand({ section: 'blog', topic: 'npm-packages', orderby: 'date', direction: 'asc' });
console.log(url); // Outputs: /blog/npm-packages?orderby=date&direction=asc
Other packages similar to url-template
uri-templates
Similar to url-template, uri-templates also implements RFC 6570 URI Template specification. It provides a similar API for parsing and expanding URI templates but might differ in specific parsing capabilities or performance optimizations.
A JavaScript URI template implementation
This is a simple URI template implementation following the RFC 6570 URI Template specification. The implementation supports all levels defined in the specification and is extensively tested.
Installation
For use with Node.js or build tools you can install it through npm:
$ npm install url-template
If you want to use it directly in a browser use a CDN like Skypack.
Example
import { parseTemplate } from 'url-template';
const emailUrlTemplate = parseTemplate('/{email}/{folder}/{id}');
const emailUrl = emailUrlTemplate.expand({
email: 'user@domain',
folder: 'test',
id: 42
});
console.log(emailUrl);
A note on error handling and reporting
The RFC states that errors in the templates could optionally be handled and reported to the user. This implementation takes a slightly different approach in that it tries to do a best effort template expansion and leaves erroneous expressions in the returned URI instead of throwing errors. So for example, the incorrect expression {unclosed
will return {unclosed
as output. The leaves incorrect URLs to be handled by your URL library of choice.