Giter Site home page Giter Site logo

serkansipahi / handlebars-intl Goto Github PK

View Code? Open in Web Editor NEW

This project forked from formatjs/handlebars-intl

0.0 1.0 0.0 630 KB

Handlebars helpers for internationalization.

Home Page: http://formatjs.io/handlebars/

License: Other

JavaScript 99.00% Shell 0.13% HTML 0.87%

handlebars-intl's Introduction

Handlebars Intl

Handlebars helpers for internationalization.

npm Version Build Status Dependency Status

Sauce Test Status

This package used to be named handlebars-helper-intl.

Overview

Goals

  • Integrate internationalization features with Handlebars to lower the barrier for localizing Handlebars templates.

  • Build on current and emerging JavaScript Intl standards — architect in a future-focused way. Leverage industry standards used in other programming langages like CLDR locale data, and ICU Message syntax.

  • Run in both Node.js and in the browser with a single <script> element.

How It Works

Template Source:

<b>Price:</b> {{formatNumber price style="currency" currency="USD"}}

Render Template:

var intlData = {
    locales: 'en-US'
}

var context = {
    price: 1000
};

var html = template(context, {
    data: {intl: intlData}
});

Output:

<b>Price:</b> $1,000.00

Features

  • Formats numbers and dates/times, including those in complex messages using the JavaScript built-ins: Intl.NumberFormat and Intl.DateTimeFormat, respectively.

  • Formats relative times (e.g., "3 hours ago") using the Intl RelativeFormat library which uses CLDR locale data.

  • Formats complex messages, including plural and select arguments using the Intl MessageFormat library which uses CLDR locale data and works with ICU Message syntax.

  • Supports formatting message strings that contain HTML via the {{formatHTMLMessage}} helper.

Usage

Intl Dependency

This package assumes that the Intl global object exists in the runtime. Intl is present in all modern browsers except Safari, and there's work happening to integrate Intl into Node.js.

Luckly, there's the Intl.js polyfill! You will need to conditionally load the polyfill if you want to support runtimes which Intl is not already built-in.

Loading Intl.js Polyfill in a browser

If the browser does not already have the Intl APIs built-in, the Intl.js Polyfill will need to be loaded on the page along with the locale data for any locales that need to be supported:

<script src="intl/Intl.min.js"></script>
<script src="intl/locale-data/jsonp/en-US.js"></script>

Note: Modern browsers already have the Intl APIs built-in, so you can load the Intl.js Polyfill conditionally, by for checking for window.Intl.

Loading Intl.js Polyfill in Node.js

Conditionally require the Intl.js Polyfill if it doesn't already exist in the runtime. As of Node <= 0.10, this polyfill will be required.

if (!global.Intl) {
    require('intl');
}

Note: When using the Intl.js Polyfill in Node.js, it will automatically load the locale data for all supported locales.

Registering Helpers in a Browser

First, load Handlebars and this package onto the page:

<script src="handlebars/handlebars.min.js"></script>
<script src="handlebars-intl/handlebars-intl.min.js"></script>

By default, Handlebars Intl ships with the locale data for English built-in to the runtime library. When you need to format data in another locale, include its data; e.g., for French:

<script src="handlebars-intl/locale-data/fr.js"></script>

Note: All 150+ locales supported by this package use their root BCP 47 langage tag; i.e., the part before the first hyphen (if any).

Then, register the helpers with Handlebars:

HandlebarsIntl.registerWith(Handlebars);

This package will create the HandlebarsIntl global that has the registerWith() function.

Registering Helpers in Node.js

Import Handlebars and this package, then register the Intl helpers with Handlebars:

var Handlebars     = require('handlebars'),
    HandlebarsIntl = require('handlebars-intl');

HandlebarsIntl.registerWith(Handlebars);

Note: in Node.js, the data for all 150+ locales is pre-loaded.

Supplying i18n Data to Handlebars

Handlebars has a data channel feature which is separate from the context a template is rendered with — it provides a side channel in which the data is piped through the template to all helpers and partials. This package uses this data channel to provide the i18n used by the helpers.

data.intl.locales

A string with a BCP 47 language tag, or an array of such strings; e.g., "en-US". If you do not provide a locale, the default locale will be used, but you should always provide one!

This value is used by the helpers when constructing the underlying formatters.

data.intl.messages

Any arbitrary data can be provided on the data.intl object; one common use is to use it hold complex message strings.

Note: These messages need to follow the ICU Message standard. Luckily this is a common standard that professional translators should already be familiar with.

// Static collection of messages, per-locale.
var MESSAGES = {
    foo: '{hostName} hosted the party!',
    bar: 'Pets? We have: {numPets, number, integer}',
    ...
}

These statically defined message strings can be provided to handlebars via data.intl.messages:

var intlData = {
    locales : 'en-US',
    messages: MESSAGES
}

var context = {...};

// Supply the `intl` `data` object when rendering the template.
var html = template(context, {
    data: {intl: intlData}
});

data.intl.formats

Object with user defined options for format styles. This is used to supply custom format styles and is useful you need supply a set of options to the underlying formatter; e.g., outputting a number in USD:

{
    number: {
        USD: {
            style   : 'currency',
            currency: 'USD'
        }
    },

    date    : {...},
    time    : {...},
    relative: {...}
}

These pre-defined formats map to their respective helpers of the same type, and any number, date, and time data.intl.formats are used by the {{formatMessage}} and {{formatHTMLMessage}} helpers. They can then be used by String name/path like this:

{{formatNumber 100 "USD"}}

Helpers

{{#intl}}

Block helper used to create a new intl data scope by updating the i18n data supplied to Handlebars within the block. This is useful when you need to render part of the page in a particular locale, or need to supply the i18n data to Handlebars via the template context — some Handlebars integrations might not support supplying options.data.intl when rendering.

The following example uses {{#intl}} to set the locale to French and will output "1 000":

{{#intl locales="fr-FR"}}
    {{formatNumber 1000}}
{{/intl}}

{{intlGet}}

Utility helper for accessing and returning the value the properties from the i18n data supplied to Handlebars via a string namespace. This provides descriptive error messages when accessing a property that is undefined, unlike Handlebars built-in data channel access syntax @.

The following are equivalent, both lookup the FOO message from data.intl.messages.FOO:

{{formatMessage (intlGet "messages.FOO")}}
{{formatMessage @intl.messages.FOO}}

Parameters:

  • namespace: String namespace to lookup a value on the data.intl object.

{{formatDate}}

Formats dates using Intl.DateTimeFormat, and returns the formatted string value.

{{formatDate now weekday="long" timeZone="UTC"}}
var intlData = {locales: 'en-US'};

var html = template({now: Date.now()}, {
    data: {intl: intlData}
});

console.log(html); // => "Tuesday, August 12, 2014"

Parameters:

  • date: Date instance or String timestamp to format.

  • [format]: Optional String path to a predefined format on data.intl.formats. The format's values are merged with any hash argument values.

Hash Arguments:

The hash arguments passed to this helper become the options parameter value when the Intl.DateTimeFormat instance is created.

{{formatTime}}

This is just like the {{formatDate}} helper, except it will reference any string-named format from data.intl.formats.time.

{{formatRelative}}

Formats dates relative to "now" using IntlRelativeFormat, and returns the formatted string value.

<p>posted {{formatRelative post.date}}</p>
var intlData: {locales: 'en-US'};

var html = template({
    post: {
        date: Date.now() - (24 * 60 * 60 * 1000) // 1 day ago.
        ...
    }
}, {
    data: {intl: intlData}
});

console.log(html); // => "<p>posted yesterday</p>"

Parameters:

  • date: Date instance or String timestamp to format relative to "now".

  • [format]: Optional String path to a predefined format on data.intl.formats. The format's values are merged with any hash argument values.

Hash Arguments:

The hash arguments passed to this helper become the options parameter value when the IntlRelativeFormat instance is created.

{{formatNumber}}

Formats numbers using Intl.NumberFormat, and returns the formatted string value.

{{formatNumber price style="currency" currency="USD"}}
var intlData = {locales: 'en-US'};

var html = template({price: 100}, {
    data: {intl: intlData}
});

console.log(html); // => "$100.00"

Parameters:

  • number: Number to format.

  • [format]: Optional String path to a predefined format on data.intl.formats. The format's values are merged with any hash argument values.

Hash Arguments:

The hash arguments passed to this helper become the options parameter value when the Intl.NumberFormat instance is created.

{{formatMessage}}

Formats ICU Message strings with the given values supplied as the hash arguments.

You have {numPhotos, plural,
    =0 {no photos.}
    =1 {one photo.}
    other {# photos.}}
{{formatMessage (intlGet "messages.photos") numPhotos=numPhotos}}
var MESSAGES = {
    photos: '...', // String from code block above.
    ...
};

var intlData = {
    locales : 'en-US',
    messages: MESSAGES
};

var html = template({numPhotos: 1}, {
    data: {intl: inltData}
});

console.log(html); // => "You have one photo."

Parameters:

  • message: String message or IntlMessageFormat instance to format with the given hash arguments as the values.

    Note: It is recommended to access the message from the i18n data supplied to Handlebars using the {{intlGet}} helper or @intl-data syntax, instead of including the literal message string in the template.

Hash Arguments:

The hash arguments represent the name/value pairs that are used to format the message by providing values for its argument placeholders.

{{formatHTMLMessage}}

This delegates to the {{formatMessage}} helper, but will first HTML-escape all of the hash argument values. This allows the message string to contain HTML and it will be considered safe since it's part of the template and not user-supplied data.

Note: The recommendation is to remove all HTML from message strings, but sometimes it can be impractical, in those cases, this helper can be used.

License

This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.

handlebars-intl's People

Contributors

ericf avatar apipkin avatar juandopazo avatar caridy avatar drewfish avatar jasonmit avatar

Watchers

Bitcollage avatar

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.