michael-brade / LaTeX.js

JavaScript LaTeX to HTML5 translator
https://latex.js.org
MIT License
736 stars 58 forks source link

Insert HTML elements from custom macro #119

Closed hypothermic closed 3 years ago

hypothermic commented 3 years ago

Is it possible to insert HTML directly from a custom marco?

I've tried using createVerbatim() but it doesn't seem to insert the element into the document:

const generator = new HtmlGenerator({
    CustomMacros: (function() {
        const args      = CustomMacros.args = {},
              prototype = CustomMacros.prototype;

        function CustomMacros(generator) {
            this.generator = generator;
        }

        args['img'] = ['HV', 'u', 'o?']
        prototype['img'] = function(url, alt) {
            console.log(`Creating image with URL "${url}" and alt text "${alt.data}"`); // this appears in console when parsing
            this.generator.createVerbatim(`<img src=${url} alt=${alt.data}/>`); // this does not appear in the final document
        };

        return CustomMacros;
    }()),
})

Any help would be appreciated @michael-brade .

michael-brade commented 3 years ago

Sure. You have to use the create... methods of HtmlGenerator. createVerbatim inserts a plain text node without style or hyphenation. (maybe that name isn't ideal... I'm not good at finding names ;-p)

michael-brade commented 3 years ago

In your case, I would suggest using create("img"). Then add your attributes.

hypothermic commented 3 years ago

I got it working, thanks for your help.

ftabashir commented 2 years ago

I tried this but was not successful. Could you please show me a working sample? @hypothermic @michael-brade

ftabashir commented 2 years ago

This is my attempt. Will not add anything to the dom.

const generator = new HtmlGenerator({
        CustomMacros: (function() {
          const args      = CustomMacros.args = {},
            prototype = CustomMacros.prototype;

          function CustomMacros(generator) {
            this.generator = generator;
          }

          args['img'] = ['HV', 'u', 'o?']
          prototype['img'] = function(url, alt) {
            this.generator.create(`img`);
          };

          return CustomMacros;
        }()),
      })