Code Monkey home page Code Monkey logo

Comments (9)

papandreou avatar papandreou commented on July 25, 2024

In a project I did at work I parsed, internationalized and reserialized the templates before passing them to htmlizer. I used memoization to prevent extra run time costs per rendering of a template.

(See lines 36--75 of formMail.js if you can gain access to the formmail.git repo).

from htmlizer.

rolandliwag avatar rolandliwag commented on July 25, 2024

That was also the only solution I had in mind outside of Htmlizer. Did you do the parsing with jsdom? I guess it's not a big deal with this requirement only being relevant in development mode but it seemed like a lot of pushing and prodding.

from htmlizer.

papandreou avatar papandreou commented on July 25, 2024

Yeah, jsdom. In formmail the same solution is used in production, but I could of course replace that with buildProduction-translated templates.

Since those lines of code don't really contain anything secret, I guess the easiest thing is to just quote them:

var memoizeAsync = require('memoizeasync'),
    memoizeSync = require('memoizesync'),
    pathModule = require('path'),
    fs = require('fs'),
    Htmlizer = require('htmlizer'),
    jsdom = require('jsdom'),
    i18nTools = require('assetgraph-builder/lib/i18nTools');

[...]
    var i18nKeys = JSON.parse(fs.readFileSync(i18nFile, 'utf-8')),
        getAllKeysForLocale = memoizeSync(function (localeId) {
            var allKeysForLocale = {},
                prioritizedLocaleIds = i18nTools.expandLocaleIdToPrioritizedList(localeId);
            for (var key in i18nKeys) {
                if (i18nKeys.hasOwnProperty(key)) {
                    for (var i = 0 ; i < prioritizedLocaleIds.length ; i += 1) {
                        if (prioritizedLocaleIds[i] in i18nKeys[key]) {
                            allKeysForLocale[key] = i18nKeys[key][prioritizedLocaleIds[i]];
                            break;
                        }
                    }
                }
            }
            return allKeysForLocale;
        }),
        memoizedLoadTemplate = memoizeAsync(function (templateName, cb) {
            fs.readFile(pathModule.resolve(__dirname, '..', 'templates', templateName + '.html'), 'utf-8', cb);
        }),
        memoizedGetTemplateRenderer = memoizeAsync(function getTemplateRenderer(templateName, localeId, cb) {
            memoizedLoadTemplate(templateName, passError(cb, function (templateSource) {
                var document = jsdom.jsdom(templateSource);
                i18nTools.eachI18nTagInHtmlDocument(document, i18nTools.createI18nTagReplacer({
                    allKeysForLocale: getAllKeysForLocale(localeId),
                    localeId: localeId
                }));
                var translatedTemplateSource = jsdom.serializeDocument(document);
                // Currently htmlizer throws away the <!DOCTYPE>, so we parse that separately and reattach it to the rendered HTML.
                // https://github.com/Munawwar/htmlizer/issues/10
                var doctype = '';
                translatedTemplateSource = translatedTemplateSource.replace(/^<!DOCTYPE[^>]*>\n?/, function ($0) {
                    doctype = $0;
                    return '';
                });
                var htmlizer = new Htmlizer(translatedTemplateSource);
                cb(null, function (obj) {
                    return doctype + htmlizer.toString(obj);
                });
            }));
        });

And then the request handler uses the async memoizedGetTemplateRenderer(templateName, localeId, cb) function to get a template renderer for a given template specialized for a given locale.

from htmlizer.

papandreou avatar papandreou commented on July 25, 2024

NB: The above code uses jsdom 2.0.0. It might not work in newer versions.

from htmlizer.

rolandliwag avatar rolandliwag commented on July 25, 2024

I guess unless @Munawwar indicates in any way his willingness to support this in some way in Htmlizer directly, I'll have to bite the bullet and squeeze it in.

jsdom any version shouldn't be an issue. As mentioned, I'm only interested in making it work for development mode anyway. Thanks for the help.

from htmlizer.

Munawwar avatar Munawwar commented on July 25, 2024

I'd prefer not to give special treatment for build tools (to keep Htmlizer generic). So I suggest using @papandreou's solution.

I can try and avoid having to reserialze to html though. Htmlizer constructor internally accepts DocumentFragment created from document object (which is created internally). I guess if I start accepting the document object itself, we can probably avoid reserialization (and also I can solve the doctype problem #10).


var htmlizer = new Htmlizer(document);

from htmlizer.

papandreou avatar papandreou commented on July 25, 2024

That sounds like a great compromise!

from htmlizer.

rolandliwag avatar rolandliwag commented on July 25, 2024

I like that idea. When will you be back from vacation?

from htmlizer.

Munawwar avatar Munawwar commented on July 25, 2024

@rolandliwag With v2, jsdom has been removed as dependency. So document (or any standard DOM objects) cannot be accepted now. So you'll have to continue serializing DOM to HTML string to achieve your use case.

Alternatively, if you rewrite i18nTools to use domhandler, then I could accept the tree (dom-like) structure which domhandler returns. (However for the sake of dev environment that would be an overkill).

from htmlizer.

Related Issues (18)

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.