1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

テンプレートエンジンでハマった

1
Last updated at Posted at 2022-05-03

C#でテンプレートエンジンを使いたい

Mustacheを以前利用していたが、もう少し高度なことをやろうと思い探したところ、ShopfyがメンテナンスしているLiquidが良さそう。

それのC#で動く版。
直近もメンテナンスされている。
https://github.com/sebastienros/fluid
が、クラスのネストしたものが表示されなかったりとやりたいことができない。

同様のプロジェクトに
https://github.com/scriban/scriban
があったが、独自過ぎるので言語を変えたいとかの場合に困るので遠慮する。

また、こちらも試してみる。
https://github.com/dotliquid/dotliquid
fluidではエラーも出なかったのが、dotliquidではエラー表示されて原因が分かった。

is invalid because it is neither a built-in type nor implements ILiquidizable

Liquizableじゃないってことなのですが、
https://github.com/dotliquid/dotliquid/wiki/DotLiquid-for-Developers
によると、
Type is an integral type (int, string, decimal, etc.), list or array of integral types, or anonymous type
タイプが限られます。

が、新しいバージョンから、
クラスに対して

    [LiquidType("*")]
    internal class MyClass
    {

のようにすれば独自クラスも使えるようになります。

テンプレートエンジンでうっかりクラス内容などを書き出してしまってセキュリティーホールにならないようにの配慮と思います。

【追記】
fluidでも同様のことがありました(まぁ、当たり前ですよねw)
https://github.com/sebastienros/fluid
こちらはエラーも出てくれなかったのと英語ちゃんと読んでませんでした。

------引用開始---------
Allow-listing object members
Liquid is a secure template language which will only allow a predefined set of members to be accessed, and where model members can't be changed. Property are added to the TemplateOptions.MemberAccessStrategy property. This options object can be reused every time a template is rendered.

Alternatively, the MemberAccessStrategy can be assigned an instance of UnsafeMemberAccessStrategy which will allow any property to be accessed.

Allow-listing a specific type
This will allow any public field or property to be read from a template.
-----引用終了----https://github.com/sebastienros/fluid

以下、DeepLの翻訳です

Allow-listing object members
Liquid は、あらかじめ定義されたメンバーへのアクセスのみを許可し、モデルのメンバーを変更できないようにする、安全なテンプレート言語です。プロパティは TemplateOptions.MemberAccessStrategy プロパティに追加されます。このオプションオブジェクトは、テンプレートがレンダリングされるたびに再利用することができます。

あるいは、MemberAccessStrategy に UnsafeMemberAccessStrategy のインスタンスを割り当てて、どのようなプロパティにもアクセスできるようにすることも可能です。

Allow-listing a specific type(特定の型のリストアップを許可する)
これは、任意のパブリック・フィールドまたはプロパティをテンプレートから読み取ることを許可します。

なので、ページにあるように、Optionを追加してやればこちらも表示されました。

こうなると、メンテナンスされているFluidの方を使おうかな。。。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?