Archive for 2月 13th, 2012

  1. Hello, StringTemplate.NET World!

    Posted on 2月 13th, 2012 by cx20

    StringTemplate.NET

    StringTemplate.NET は Java 用のテンプレートエンジン「StringTemplate」の .NET 実装である。

    ソースコード(テンプレート)

    <html>
      <head>
        <title>Hello, World!</title>
      </head>
      <body>
        <p>Hello, $message$ World!</p>
      </body>
    </html>

    ソースコード(C#)

    using System;
    using System.IO;
    using System.Diagnostics;
    using Antlr3.ST;
    using Antlr3.ST.Language;
     
    public partial class _Hello : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                String template = Server.MapPath("templates");
                StringTemplateGroup group = new StringTemplateGroup("group", template);
                StringTemplate st = group.GetInstanceOf("hello");
                st.SetAttribute("message", "StringTemplate.NET");
                Response.Write(st);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
            }
        }
    }

    実行方法

    ディレクトリ構成
    /Hello               … 公開用フォルダ
        /Hello.aspx
        /Hello.aspx.cs
        /Web.config      … ASP.NET 構成ファイル
        /bin
             /Antlr3.Runtime.dll
             /Antlr3.StringTemplate.dll
        /templates      … テンプレート配置場所
              /hello.st
     
    1. テンプレートの配置
       templates
    2. ブラウザで表示
       http://localhost/Hello/Hello.aspx

    実行結果

    Hello, StringTemplate.NET World!