Reputation: 2850
I am working on a project that uses Katex format to display mathematical formulas.
Now I am facing a bit of a problem here.
For rendering a fraction the katex syntax is
\dfrac{x}{y}
Now if I have a variable x of value 3 and another variable y of value 5.
How would I inject the values into the Katex syntax?
I want to have something like
var x = 3;
var y = 5;
\dfrac{x}{y}
where the x and y in katex syntax will be replaced by the actual values.
Note: I am also using the https://github.com/talyssonoc/react-katex
to render Katex.
Upvotes: 0
Views: 966
Reputation: 60968
I think I'd use macro substitution for this. Try to get your formula expressed as \frac{\x}{\y}
by whatever machinery is generating the formula. Then you can substitute either the variable names or the values in place of those macros. Something like this:
katex.render("\\frac{\\x}{\\y}", element, {
macros: {
"\\x": String(x),
"\\y": String(y),
}
});
If you don't have a way to control how the formulas are constructed initially, this merely shifts the problem from substituting values into the formula to substituting commands into it. In that case, you probably want to tokenize the input string into commands \…
and other letters. Commands remain as they are, while other letters are subject to variable substitution.
One thing to be careful of is grouping: Input \frac xy
renders just fine, but with x=34.5
and y=5.67
substituted in the naive way, the result \frac 34.55.67
(which is what both text and macro substitution will give you) renders as \frac{3}{4}.55.67
. So make sure that each macro you have in your formula is enclosed by {…}
or add another level of {…}
when you do the substitution as in "\\x": "{" + x + "}"
. Enclosing macros by {…}
inside the formula has the benefit that you won't have to worry about a macro eating a subsequent space: \text{\x is 2}
is bad but \text{{\x} is 2}
is better.
But even with grouping done correctly, this approach is not perfect since not all non-commands are indeed variables. For example with \begin{array}{rlrl}…\end{array}
neither the a
in array
nor the r
in rlrl
should be considered a variable. Fixing this is really problematic, as it requires a lot of semantic insight.
One way to tackle this dilemma would be letting KaTeX do its rendering and then doing the substitution in the resulting DOM subtree. You should be able to identify variables as <span class="mord …">…</span>
(mord
stands for math ordinary). This means you depend on the exact representation KaTeX uses for its output, so you should make sure you run a fixed version of KaTeX as these internal things are subject to change without notice. Also be aware of the fact that in some (possibly future) version this might break certain constructs which depend on the width of a given box, although even things as problematic as \underbrace
appear to work with this substitution approach at the moment.
Upvotes: 3