我正在使用模板生成TeX文件,并使用Mustache渲染该模板。
首先,我在DataFrame中有数据:
Row │ label │ score │ max │
│ │ Int64 │ Int64 │ Int64 │
├─────┼───────┼───────┼───────┤
│ 1 │ 1 │ 2 │ 4 │
│ 2 │ 2 │ 3 │ 5 │
│ 3 │ 3 │ 4 │ 6 │
│ 4 │ 4 │ 5 │ 7 │
和字典:
student = Dict( "name" => "John", "surname" => "Smith");
我想呈现一个模板,以便在模板中替换字典变量和DataFrame变量。可以同时使用字典或DataFrame,但不能同时使用两者。
例如,渲染仅在具有以下所示模板'tmpl'的DataFrame上工作:
tmpl = """
Your marks are:
\\begin{itemize}
{{#:D}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/:D}}
"""
rendered_marks = render(tmpl, D=df );
但是,当我从“学生”字典中添加诸如:name或:surname之类的变量时,会出现错误消息:
marks_tmpl = """
Hello \\textbf{ {{:name}}, {{:surname}} }
Your marks are:
\\begin{itemize}
{{#:D}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/:D}}
\\end{itemize}
\\end{document}
"""
rendered_marks = render(tmpl, student, D=df );
正确的方法是什么?
答案 0 :(得分:1)
不允许混用Dict
和关键字参数。最简单的方法是将DataFrame添加到字典中。
首先,创建您的DataFrame
:
df = DataFrame(label=1:4, score=2:5, max=4:7)
4×3 DataFrame
│ Row │ label │ score │ max │
│ │ Int64 │ Int64 │ Int64 │
├─────┼───────┼───────┼───────┤
│ 1 │ 1 │ 2 │ 4 │
│ 2 │ 2 │ 3 │ 5 │
│ 3 │ 3 │ 4 │ 6 │
│ 4 │ 4 │ 5 │ 7 │
接下来,在字典中引用DataFrame
进行Mustache.jl渲染:
student = Dict( "name" => "John", "surname" => "Smith", "df" => df);
marks_tmpl = """
Hello \\textbf{ {{name}}, {{surname}} }
Your marks are:
\\begin{itemize}
{{#df}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/df}}
\\end{itemize}
"""
通过这种方式,字典和DataFrame
变量都被呈现:
julia> println(render(marks_tmpl, student))
Hello \textbf{ John, Smith }
Your marks are:
\begin{itemize}
\item Mark for question 1 is 2 out of 4
\item Mark for question 2 is 3 out of 5
\item Mark for question 3 is 4 out of 6
\item Mark for question 4 is 5 out of 7
\end{itemize}
我想这就是你想要的吗?
答案 1 :(得分:1)
要添加到答案中,您还可以使用迭代器来访问字典中的键或名为tuple的键:
tmpl = """
Hello {{#:E}}\\textbf{ {{:name}}, {{:surname}} }{{/:E}}
Your marks are:
\\begin{itemize}
{{#:D}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/:D}}
\\end{itemize}
\\end{document}
"""
using Mustache
using DataFrames
student = Dict( "name" => "John", "surname" => "Smith");
D = DataFrame(label=[1,2], score=[80,90])
Mustache.render(tmpl, E=(name="John",surname="Doe"),D=D, max=100)