代码之家  ›  专栏  ›  技术社区  ›  NewbiZ

目标C内置模板系统?

  •  6
  • NewbiZ  · 技术社区  · 15 年前

    我正在开发一个iPhone应用程序,我使用HTML来显示格式化的文本。

    我经常显示同一个网页,但内容不同。我想使用一个模板HTML文件,然后用我的不同值填充它。

    我想知道Objective-C是否有一个类似于Ruby中erb的模板系统。

    这样就可以做

    模板:

    <HTML>
      <HEAD>
      </HEAD>
      <BODY>
        <H1>{{{title}}}</H1>
        <P>{{{content}}}</P>
      </BODY>
    </HTML>
    

    目标C(或理想世界中的目标C)

    Template* template = [[Template alloc] initWithFile:@"my_template.tpl"];
    [template fillMarker:@"title" withContent:@"My Title"];
    [template fillMarker:@"content" withContent:@"My text here"];
    [template process];
    NSString* result = [template result];
    [template release];
    

    结果字符串将包含:

    <HTML>
      <HEAD>
      </HEAD>
      <BODY>
        <H1>My Title</H1>
        <P>My text here</P>
      </BODY>
    </HTML>
    

    上面的例子可以通过一些文本替换来实现,但是维护起来会很困难。 我还需要一些类似于模板内部循环的东西。例如,如果要显示多个项目,我希望生成多个div。

    感谢阅读:)

    7 回复  |  直到 15 年前
        1
  •  8
  •   darrinm    13 年前

    您是否考虑将其用作模板:

    <HTML>
      <HEAD>
      </HEAD>
      <BODY>
        <H1>%@</H1>
        <P>%@</P>
      </BODY>
    </HTML>
    

    然后:

    // just to get file name right
    NSString* fn = 
        [NSString stringWithFormat:@"%@/my_template.tpl", 
                  [[ NSBundle mainBundle ] resourcePath ]];
    // template
    NSError *error;
    NSString* template = 
        [NSString stringWithContentsOfFile:fn 
                  encoding:NSUTF8StringEncoding error:&error];
    // result
    NSString* result = 
        [NSString stringWithFormat:template, 
                  @"MyTitle", 
                  @"MyText"];
    

    我觉得这正是你想要的。

    当然,您必须在项目中添加模板文件作为资源。

        2
  •  3
  •   Gwendal Roué    14 年前
        3
  •  2
  •   Chuck    15 年前

    不,Objective-C没有内置模板系统。一般来说,对于简单的用法,您只需使用文本替换(可能通过 stringWithFormat: )对于更高级的系统,您可以选择一个完全适合您需要的模板系统。

        5
  •  2
  •   xhan    11 年前

    下面是一个用于Objective-C的轻量级模板引擎: CCTemplate

        6
  •  0
  •   Johnd    8 年前

    在斯威夫特3.1

    var fn: String = "\(Bundle.main.resourcePath)/my_template.tpl"
    // template
    var error: Error?
    var template = try? String(contentsOfFile: fn, encoding: String.Encoding.utf8)
        // result
    var result = String(format: template, "MyTitle", "MyText")
    
        7
  •  -3
  •   Pear Johan    11 年前

    对于很多人来说,这可能是不太可能的选择,但我需要模板来生成代码,并选择使用Java+FTP, http://freemarker.org/libraries.html

    我最终得到了一个工具来生成表视图、表单视图、集合视图、基于数据模型xcdatamodeld文件的谷歌驱动器集成。