0

我正在使用 dmustache ( https://github.com/synopse/dmustache ) 来呈现一些模板。我想知道如果字符串变量是空字符串,怎么不能渲染某个部分。

这个简化的程序呈现FirstName: Joe MiddleName: LastName: Doe,但我想拥有FirstName: Joe LastName: Doe,因为没有 MiddleName (只有在这种情况下)。

program P;

uses
  System.SysUtils, SynMustache, SynCommons;

const
  TEMPLATE = 'FirstName: {{FIRSTNAME}} {{#MIDDLENAME}}MiddleName: {{MIDDLENAME}}{{/MIDDLENAME}} LastName: {{LASTNAME}}';
var
  Mustache: TSynMustache;
  Content: Variant;
begin
  Mustache := TSynMustache.Parse(TEMPLATE);
  TDocVariant.New(Content);
  Content.FirstName := 'Joe';
  Content.MiddleName := '';
  Content.LastName := 'Doe';
  WriteLn(Mustache.Render(Content));
  ReadLn;
end.

使用模板中的部分不会改变结果

TEMPLATE = 'FirstName: {{FIRSTNAME}} {{#MIDDLENAME}}MiddleName: {{MIDDLENAME}} {{/MIDDLENAME}}LastName: {{LASTNAME}}';
4

1 回答 1

0

我找到了两种方法来解决这个问题。首先是在模板中使用条件,例如

TEMPLATE = 'FirstName: {{FIRSTNAME}} {{#if MIDDLENAME <> ""}}MiddleName: {{MIDDLENAME}} {{/if}}LastName: {{LASTNAME}}';

为此,还必须通过标准助手调用渲染,比如

Mustache.Render(Content, nil, TSynMustache.HelpersGetStandardList)

第二个是将内容变量设置为 NULL 而不是空字符串(或根本不设置)并使用节(注意节{{.}}内的自我引用)

const
  TEMPLATE = 'FirstName: {{FIRSTNAME}} {{#MIDDLENAME}}MiddleName: {{.}} {{/MIDDLENAME}}LastName: {{LASTNAME}}';
var
  Mustache: TSynMustache;
  Content: Variant;
begin
  Mustache := TSynMustache.Parse(TEMPLATE);
  TDocVariant.New(Content);
  Content.FirstName := 'Joe';
  Content.MiddleName := NULL; //you can also comment this line
  Content.LastName := 'Doe';
  WriteLn(Mustache.Render(Content));
  ReadLn;
end.
于 2018-03-01T14:48:47.717 回答