lukasgeiter / gettext-extractor

A flexible and powerful Gettext message extractor with support for JavaScript, TypeScript, JSX and HTML.
MIT License
98 stars 21 forks source link

Support for Handlebar syntax. {{#translate}} Hello world {{/translate}} #28

Open chriscodeweb opened 5 years ago

chriscodeweb commented 5 years ago

Hello, I have succesfully implemented your extractor. Great work btw! 👍 Unfortunately I can't use element tags in my html template because I use handlebar for translations. Is it possible to use the createHtmlParser but then for a non element, but a partial string? In my case I have to scan for {{#translate}} Hello world {{/translate}} I could fork your repository, and try to create scan for this but could you point me in the right direction where I could make the adjustment?

lukasgeiter commented 5 years ago

Hi! Implementing support for Handlebars using the HTML parser would likely lead to bad performance and would entail parsing Handlebars syntax using regex. However, it should be possible to use the official Handlebars parser instead.

For the next release I'm actually planning to add more parsers/extractors and make it easier to extend in the future. I'll definitely look into adding Handlebars support as well.


In the meantime, you can try getting it working using a custom HTML extractor if you want:

extractor
    .createHtmlParser([
        (node, fileName, addMessage) => {
            if (node.nodeName === '#text') {
                let content = node.value;

                // extract message using regex...

                if (message) {
                    addMessage({
                        text: message
                    });
                }
            }
        }
    ]);
chriscodeweb commented 5 years ago

Thanks a lot Lukas! I finally changed the code to this to make it work :) Amazing job to write this scanner! Definitely black belt level coding 👍 I feel like a white belt now haha

.createHtmlParser([
    (node, fileName, addMessage) => {
        if (node.nodeName === '#text') {
            let content = node.value;
            if(content.indexOf('#translate') !== -1 ) {
                let re = /{{#translate}}(.*?){{\/translate}}/g;
                content.match(re).map(function(value){
                    let newValue = value.replace(/{{#translate}}|{{\/translate}}/g, '').trim();
                    addMessage( {
                        text: newValue
                    })
                });
            }
        }
    }
])