localize

package module
v0.0.0-...-1599bd7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2019 License: MIT Imports: 6 Imported by: 0

README

Localize

Package localize provides functions for translating Golang data structures to JavaScript primitives. The translated, or "localized", JavaScript that can be produced by this package is intended to be used directly with the html/template package. This package eases the process of passing global data down to front-end scripts.

Installation

Run go get github.com/foresthoffman/localize

Importing

Import the package by including github.com/foresthoffman/localize in your import block.

e.g.

package main

import(
	...
	"github.com/foresthoffman/localize"
)

Usage

Here's a simple example of the syntax:

import(
    "github.com/foresthoffman/localize"
)

func main() {
    // Generates a new localization map with the provided data.
    dataMap, err := localize.NewMap(
        // This will tell the localizer to assign the data to
        // the "_localData" global JavaScript variable.
        "_localData",
        localize.Data{
            "motd": "Hello world, welcome to a new day!",

            // "nonce" will hold an object with an element with
            // the key, "login", and the value,
            // "LaKJIIjIOUhjbKHdBJHGkhg"
            "nonce": map[string]string{
                "login": "LaKJIIjIOUhjbKHdBJHGkhg",
            },
        },
    )

    // ...proper error handling, data manipulation, etc.
}

For a more complex example using the standard html/template and net/http packages check the test/template.go file.

How exactly are Golang data types translated to JavaScript?

localize.ReflectTarget() is the function that handles this process. From the docs:

[ReflectTarget takes] a reflect.Value object and recursively determines the values of all the fields, sub-fields, elements, etc. At each step, the target's type is analyzed to see whether or not it's an enclosing type. If the target is an enclosing type, then the contents of the target will be wrapped appropriately. Square-brackets ("[]") are used for translating data to a JavaScript array. Curly-brackets ("{}") are used for translating data to a JavaScript object. Non-enclosing types [e.g. int, float64, and string] simply output according to their JavaScript equivalent. The complete contents of the top-most target is written piece-by-piece to the buffer provided.

Localized Golang interfaces are translated to JavaScript as native objects. As in, they are of type Object, but do not carry over their interface's context. So, if an instance of a struct Page were placed in a localize.Map, the JavaScript equivalent would not provide any explicit indication that the Object was a Page.

That's all, enjoy!

Documentation

Overview

Package localize provides functions for translating Golang data structures to JavaScript primitives. The translated, or "localized", JavaScript that can be produced by this package is intended to be used directly with the html/template package. This package eases the process of passing global data down to front-end scripts.

Here's a simple example of the syntax:

import(
    "github.com/foresthoffman/localize"
)

func main() {
    // Generates a new localization map with the provided data.
    dataMap, err := localize.NewMap(
        // This will tell the localizer to assign the data to
        // the "_localData" global JavaScript variable.
        "_localData",
        localize.Data{
            "motd": "Hello world, welcome to a new day!",

            // "nonce" will hold an object with an element with
            // the key, "login", and the value,
            // "LaKJIIjIOUhjbKHdBJHGkhg"
            "nonce": map[string]string{
                "login": "LaKJIIjIOUhjbKHdBJHGkhg",
            },
        },
    )

    // ...proper error handling, data manipulation, etc.
}

For a more complex example using the standard html/template and net/http packages check the test/template.go file.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrReservedKeyword     = fmt.Errorf("Reserved variable name provided")
	ErrInvalidVariableName = fmt.Errorf("Invalid variable name provided")
	ErrInvalidKey          = fmt.Errorf("Invalid key name provided")
	ErrInvalidData         = fmt.Errorf("Invalid data provided")

	// ErrNilMap most likely indicates that NewMap() was
	// provided with a nil pointer.
	ErrNilMap = fmt.Errorf("Nil data map field")
)
View Source
var JSReservedRegex = regexp.MustCompile(`^(break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|void|while|with|yield|enum|await|implements|interface|package|private|protected|public|static)$`)

JSReservedRegex matches reserved JavaScript keywords that may not be used as variable names. Reserved keyword documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords

View Source
var JSVariableRegex = regexp.MustCompile(`^[a-zA-z_\$][a-zA-z_\$0-9]*$`)

JSVariableRegex matches a valid JavaScript variable name. Variable name documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables

Functions

func ReflectTarget

func ReflectTarget(target reflect.Value, buf *bytes.Buffer)

ReflectTarget takes a reflect.Value object and recursively determines the values of all the fields, sub-fields, elements, etc. At each step, the target's type is analyzed to see whether or not it's an enclosing type. If the target is an enclosing type, then the contents of the target will be wrapped appropriately. Square-brackets ("[]") are used for translating data to a JavaScript array. Curly-brackets ("{}") are used for translating data to a JavaScript object. Non-enclosing types simply output according to their JavaScript equivalent.

The complete contents of the top-most target is written piece-by-piece to the buffer provided.

Types

type Data

type Data = map[string]interface{}

Data is an alias for an interface map.

type Localizer

type Localizer interface {
	// Data manipulation.
	Add(key string, data interface{}) error
	Delete(key string) error
	GetData() Data

	// Namespacing.
	SetGlobalName(name string) error
	GetGlobalName() string

	// Localization.
	JS() template.JS
}

Localizer describes a struct that localizes Golang data.

type Map

type Map struct {
	// contains filtered or unexported fields
}

Map takes a set of data, translates it to JavaScript primitives, and then formats it for insertion into a global browser context.

func NewMap

func NewMap(name string, data Data) (*Map, error)

NewMap generates a new localization map.

func (*Map) Add

func (l *Map) Add(key string, data interface{}) error

Add inserts an element with the specified key to the data map.

func (*Map) Delete

func (l *Map) Delete(key string) error

Delete removes an element with the specified key from the data map.

func (*Map) GetData

func (l *Map) GetData() Data

GetData retrieves the localization map's data.

func (*Map) GetGlobalName

func (l *Map) GetGlobalName() string

GetGlobalName retrieves the localization map's global JavaScript variable name.

func (*Map) JS

func (l *Map) JS() template.JS

JS gets a valid block of template.JS data that represents the fields of this Map's "data" field and all its children. The returned template.JS block can be directly placed into an HTML template (provided by the "html/template" package) and output as valid JavaScript code.

func (*Map) SetGlobalName

func (l *Map) SetGlobalName(name string) error

SetGlobalName assigns the localization map's global JavaScript variable name, which will receive the localized data.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL