GithubHelp home page GithubHelp logo

sindresorhus / pupa Goto Github PK

View Code? Open in Web Editor NEW
356.0 7.0 22.0 21 KB

Simple micro templating

License: MIT License

JavaScript 93.53% TypeScript 6.47%
template-engine template-library templating template- placeholder interpolation npm-package string

pupa's Introduction

pupa

Simple micro templating

Useful when all you need is to fill in some placeholders.

Install

npm install pupa

Usage

import pupa from 'pupa';

pupa('The mobile number of {name} is {phone.mobile}', {
	name: 'Sindre',
	phone: {
		mobile: '609 24 363'
	}
});
//=> 'The mobile number of Sindre is 609 24 363'

pupa('I like {0} and {1}', ['๐Ÿฆ„', '๐Ÿฎ']);
//=> 'I like ๐Ÿฆ„ and ๐Ÿฎ'

// Double braces encodes the HTML entities to avoid code injection.
pupa('I like {{0}} and {{1}}', ['<br>๐Ÿฆ„</br>', '<i>๐Ÿฎ</i>']);
//=> 'I like &lt;br&gt;๐Ÿฆ„&lt;/br&gt; and &lt;i&gt;๐Ÿฎ&lt;/i&gt;'

Note: It does not support nesting placeholders: pupa('{phone.{type}}', โ€ฆ)

API

pupa(template, data, options?)

template

Type: string

Text with placeholders for data properties.

data

Type: object | unknown[]

Data to interpolate into template.

The keys should be a valid JS identifier or number (a-z, A-Z, 0-9).

options

Type: object

ignoreMissing

Type: boolean
Default: false

By default, Pupa throws a MissingValueError when a placeholder resolves to undefined. With this option set to true, it simply ignores it and leaves the placeholder as is.

transform

Type: ((data: {value: unknown; key: string}) => unknown) | undefined (default: ({value}) => value)

Performs arbitrary operation for each interpolation. If the returned value was undefined, it behaves differently depending on the ignoreMissing option. Otherwise, the returned value will be interpolated into a string (and escaped when double-braced) and embedded into the template.

MissingValueError

Exposed for instance checking.

FAQ

What about template literals?

Template literals expand on creation. This module expands the template on execution, which can be useful if either or both template and data are lazily created or user-supplied.

Related

pupa's People

Contributors

apsknight avatar bendingbender avatar peteruithoven avatar richienb avatar sindresorhus avatar yuhr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

pupa's Issues

Support functions in templates

Hi, u can add support functions in templates?

Example:

const template = 'Some string via { obj.method() }'

const data = {
 obj: { 
  method: () => 'great function' 
 } 
}

pupa(template, data)

Encoding as HTML Entities to avoid code injection

If the output is for a browser, then it can be a security issue (code injection, etc.) if the values are simply dumped straight into the output - rather, they should be encoded as HTML entities. To that end, it's annoying doing it oneself before passing data to the templating engine. Is it planned to add support for this directly to pupa?

e.g. Maybe single braces {} means do it normally, and double braces ({{}}) could mean "escape it too please"? Or even the other way around.

Please update minimal version of 'escape-goat' to 4.0.0

Could you please set the minimal version for dependency escape-goat to 4.0.0. Because from v4 it became a true ESM module.

"dependencies": {		
  "escape-goat": "^4.0.0"
},

Btw, would be awesome to convert this library to an ESM module too.

Transpiling with rollup

In order to use this simple plugin within other modules, it would be best if it was transpiled using rollup to be browser and import ready.

I could definitely make a PR for this but I wanted to ask if it made sense first.

Escape dot character

Hi guys,
Sometimes, my data is an object that includes a dot character.

pupa('The mobile number of {name} is {phone\.mobile}', {
    name: 'Sindre',
    "phone.mobile": "609 24 363"
});

Maybe should be supported \ character to escape the dot character.

Template matches incorrect values making them undefined.

I have a package.json file in which I want to replace only name field of it.
It's all good, but I also have entries like

  "lint-staged": {
    "*.{json,md,css,graphql,html}": [
      "prettier --write"
    ],
    "*.{ts,js,jsx,tsx}": [
      "eslint --fix --ext js,jsx,tsx,ts --max-warnings 0"
    ]
  },

So these glob patterns transform info undefined

  "lint-staged": {
    "*.undefined": [
      "prettier --write"
    ],
    "*.undefined": [
      "eslint --fix --ext js,jsx,tsx,ts --max-warnings 0"
    ]
  },

I'm unsure of it's expected behavior as inside there are no dots as a separators but commas.

Support filters

Many templating languages support filtering individual interpolated values:

"Hello, {name | capitalize}!"
//=> with {name: "john doe"} => "Hello, John Doe!"

pupa supports transforming all values, but not individual ones. The regex to match items could be modified to:

/{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)(?: \| [^ }]+)*}/gi

This would match an arbitrary number of filters separated by |. (regex101)

Filters would just be an object of functions passed to pupa and would be applied in order from left to right. Filters in the template without a match could have the same semantics as a missing value (either get ignored or throw, perhaps with a new MissingFilterError).


Related, some further improvements to the regex could be supporting arbitrary whitespace and characters:

/{\s*([^\s}|]+)\s*(?:\|\s*[^}]+\s*)*}/gi

template doesn't match camel case variables

This is happening since v2.0.1...v2.1.0

const pupa = require('pupa')

const result = pupa('The mobile number of {name} is {opts.phoneNumber}', {
  name: 'Sindre',
  opts: {
    phoneNumber: '609 24 363'
  }
})

console.log(result) // => The mobile number of Sindre is {opts.phoneNumber}

The model does not match property keys with the dynamic name.

Hi. ๐Ÿ˜Š
I'm using pupa in a discord bot in a multi-language system. ๐Ÿค–

The files containing the translations are made up of objects with properties whose keys contain names with special characters such as spaces and -.

However, the formatter does not find these properties. I added a simple code below simulating the environment. ๐Ÿ˜…

var pupa = require("pupa")

const args = {
   "commonName": {
      test: 1
   },
   "dynamic-key-name": {
      test: 2
   },
   "dynamic key name": {
      test: 2
   }
}

console.log(pupa("testing {commonName.test}", args))         //=> "testing 1"
console.log(pupa("testing {dynamic-key-name.test}", args))   //=> "testing {dynamic-key-name.test}"
console.log(pupa("testing {dynamic key name.test}", args))   //=> "testing {dynamic key name.test}"

Feature request: reentrant templates

pupa('Number is {phone.{type}}', {
  type: 'mobile',
  phone: {
    mobile: '333',
    home: '444'
  }
})
// => 'Number is {phone.mobile}'
// Would be amazing if this was:
// => 'Number is 333'

Include GitHub topics

I could not remember the project name and had to find it manually to recommend it to a friend.

Does not support non-english letters?

Hi! Thanks for providing a useful lib! ๐Ÿ‘

I discovered today that it seems as if names which contains Swedish letters รฅรครถ does not work. This is unfortunate, and I suspect this extends to other non-english letters as well?

I always use English when naming variables, but not in this case since these placeholders are to be used in a (Swedish) text context. So instead of using {owner} I really want to use {รคgare} (= owner in Swedish). This is useful because it makes it easier to adhere to correct grammar etc. and improves the experience for non-technical colleagues.

parse JSON and `pupa` its strings

I think it would be great to add a simple JSON parser, where for all strings, pupa looks for placeholders and replace the first all compatible placeholders (based on user choice).

Motivation:
I would like to use pupa with node-config to load JSON configuration files and also supply other secret environment variables.

Can't get real return values

I can not get real return values, because of this code return result || ''

if result to Boolean is false, i got ''. like 0, false, null, undefined...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.