Model to Text工具Acceleo使用教程(四)——模板语法

  从这一讲开始,将介绍模板设计的语法,以便大家可以设计自己需要的模板,完成需要的代码生成。下面主要从两方面讲解语法和服务。

一、语法

  Acceleo的变量区是用<%和%>包围的,当然为了避免某些冲突(例如jsp生成代码中也包含<%这样的标记),也可以用另一种标记[%和%]包围,编译器会自动识别标记。

1、注释

  Acceleo的注释用<%--和--%>包围,可以一行或者多行。

2、metamodel

  关键字metamodel指定了模板中使用的元模型,它是import区的第一条命令,语法如下:

  <%
  metamodel MyMetaModelURI
  import..
  %>

  元模型的URI(统一资源标识符)指定了我们将要使用什么样的元模型,下面是常用元模型的URI:

  - UML 1.4 meta model: http://www.obeo.fr/acceleo/uml14
  - UML 1.3 meta model: http://www.obeo.fr/uml13
  - UML 2.0 meta model: http://www.eclipse.org/uml2/1.0.0/UML or http://www.eclipse.org/uml2/2.0.0/UML
  - Ecore meta-model: http://www.eclipse.org/emf/2002/Ecore

  应用举例:

  <%
  metamodel http://www.obeo.fr/uml14
  import fr.obeo.template.commonScript
  import fr.obeo.services.StringServices
  %>

  上面的脚本说明了我们用的元模型是UML1.4。

3、import

  和java语言的import类似,acceleo的import命令用在import区,通过import可以链接到其它模板或服务文件,然后调用链接文件中的脚本或服务。语法如下:

  <%
  metamodel..
  import myPackage.myServicesClass
  import myPackage. myScriptTemplate
  %>

  其中myPackage是文件路径(例如fr.obeo.acceleo),myServicesClass和myScriptTemplate分别java类的名字和模板的名字。

  应用举例:

  <%
  metamodel http://www.obeo.fr/uml14
  import fr.obeo.template.commonScript
  import fr.obeo.services.StringServices
  %>

  表示本文件的脚本可以调用commonScript.mt中定义的脚本,也可以调用StringServices.class中定义的服务。

4、script

  script可以用于标识不同的脚本以及它使用的对象类型,语法如下:

  <%script type=”myType” name=”identifier” file=“nameOfGeneratedFile” description=“ myDescription ” post="myPost"%>

  myType是脚本将要使用的对象类型,identifier是一个字符串,可以用于标识脚本,nameOfGeneratedFile是生成的代码文件的相对路径(包含扩展名),myDescription 描述了脚本的动作,myPost是一个函数,在模板使用完成时调用。

  其中的type和name参数是必须有的,其它是可选的。参数对("type","name")标识不同的脚本,对于给定的不同type,脚本(对参数对)必须不同。参数file中可以调用其它脚本。

5、for

  acceleo的for语法如下:

  <%for (对象列表) {%>
  对每个对象的操作
  <%}%>

  对象列表可以是acceleo的对象integer(“ int ”), Boolean (“boolean”), string (“ String ”), list (“ ENodeList ”),也可以是EMF (“ EObject ”)。

  应用举例:

  <%for (eAllContents(“ Class ”)) {%>
  The name of the class is: <%name%>.
  <%}%>

  此脚本表示输出每个class的名字,关于eAllContents服务将会在后面讲解。

6、if

  acceleo的if语法如下:

  <%if (BooleanExpression) {%>
  BooleanExpression为真时执行的命令
  <%} else {%>
  BooleanExpression为假时执行的命令
  <%}%>

  BooleanExpression返回的布尔值,其中的操作符可以用== (equal), != (different), < (less than), <= (less or equal than), > (greater than >= (greater than or equal), || (logical or), && (logical and) and ! (negation),其中的操作数可以用脚本、服务或链接元模型的值、对象和调用。

  应用举例:

  <%if (hasStereotype(“ Entity ”)) {%>
  public List myList = new ArrayList();
  <%} else {%>
  public String myString = “”;
  <%}%>

二、总结

  本讲介绍了acceleo的基本语法,后面将介绍acceleo模板提供的基本服务。

原文地址:https://www.cnblogs.com/jpcflyer/p/2513623.html