0

Researching some ways to generate a .tex file and subsequently a PDF, I found a beautiful pythonic method of string interpolation that I've never seen before, specifically in this SO question here:

import argparse

content = r'''\documentclass{article}
\begin{document}
... P \& B 
\textbf{\huge %(school)s \\}
\vspace{1cm}
\textbf{\Large %(title)s \\}
...
\end{document}
'''

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--course')
parser.add_argument('-t', '--title')
parser.add_argument('-n', '--name',) 
parser.add_argument('-s', '--school', default='My U')

args = parser.parse_args()

with open('cover.tex','w') as f:
    f.write(content%args.__dict__) #This!

Is there any way of implementing the pythonic solution above in JavaScript?

Daniel
  • 67
  • 1
  • 1
  • 7
  • That'll work just fine in JS, the only difference is that it requires `$` before the `{}`s to interpolate..? – CertainPerformance Jan 07 '22 at 02:53
  • @CertainPerformance I will edit my question so that it is more clear. I want to implement the FIRST example in JavaScript, not the example explaining what I know about JS string interpolation... – Daniel Jan 07 '22 at 02:56
  • I'm not understanding what the issue is. All you need to do is change, eg `content = r'''\documentclass{article}` to ``const content = String.raw`\documentclass${article}`` and continue the pattern (the backslashes create problems) – CertainPerformance Jan 07 '22 at 02:58
  • @CertainPerformance that is not what is being interpolated in the code above, ie ```%(school)s``` was interpolated by the corresponding value of the key "school" in ```args.__dict__``` . Are you saying that replacing ```%(school)``` with ```${school}``` works? – Daniel Jan 07 '22 at 03:03
  • Yes, interpolate in template literals in JS with `$(varName}`, as you showed in the original version of your question - that'll work just fine – CertainPerformance Jan 07 '22 at 03:05
  • Lets say I have corrected it that way, and I have some arbitrary ```const dict = {"school": "my University" }``` , how is it that I emulate the python line ```f.write(content%args.__dict__)```? That is my confusion. Thank you for being patient with me! – Daniel Jan 07 '22 at 03:11
  • If the object is completely dynamic, then you won't be able to reference the interpolated values as identifiers. You'll probably need something like [this](https://stackoverflow.com/a/57565813) – CertainPerformance Jan 07 '22 at 03:15
  • That's a lot closer to what I'm trying to do, thank you very much! – Daniel Jan 07 '22 at 03:32

0 Answers0