DEV Community

Cover image for Localizing Go to JavaScript
Forest Hoffman
Forest Hoffman

Posted on • Edited on

7

Localizing Go to JavaScript

While working a Go backend for a side-project, I implemented a custom templating system among other things. For my project, I needed to be able to pass nonce values down to my JavaScript. I realized that keeping the data in the front-end up-to-date with the backend would require a lot of leg work. In order to save time and effort, I built the localize package.

This package takes a pre-defined Go data structure and recursively translates it to JavaScript primitives. The JavaScript that is spit back out can be used in just about any fashion, but it is designed to work best with the html/template package. Since the html/template package provides support for calling functions assigned to data passed to the template.Template.Execute() function, templates can fire off the localization process themselves. Once you have a template setup to utilize the localize package, it's a fire and forget situation. The best kind, in my opinion.

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.
}
Enter fullscreen mode Exit fullscreen mode

EDIT (08/11/19): test/template.go provides a very handy example of using localize with an actual HTTP server.

Credits

Photo by MW on Unsplash

That's it! :)

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay