如何在 Julia 语言中使用 Mustache.jl 呈现的字典和 DataFrame?

How to use both dictionary and DataFrame with Mustache.jl rendering in Julia language?

我正在使用模板生成 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 );

但是,当我从 'student' 字典中添加诸如 :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 );

正确的做法是什么?

您不能混合使用 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}

我猜这就是你想要的?

为了增加答案,您还可以使用可迭代对象访问字典中的键或命名为元组:

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)