精华内容
下载资源
问答
  • engine template option(s)

    2020-11-27 11:20:59
    <div><p>allow passing parameter to engine template while using this.template <em>.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, ...
  • <p>If you employ percent signs then this will break essentially all upstream or downstream processing of the template files using XML tools, missing a bunch of interoperability and important ...
  • The template engine

    2019-09-29 08:24:05
    Play has an efficient templating system which allows to dynamically generate HTML, XML, JSON or any text-based formatted document. The template engine usesGroovyas an expression language. A tag...

    Play has an efficient templating system which allows to dynamically generate HTML, XML, JSON or any text-based formatted document. The template engine uses Groovy as an expression language. A tag system allows you to create reusable functions.

    Templates are stored in the app/views directory.

    Template syntax

    A template file is a text file, some parts of which have placeholders for dynamically generated content. The template’s dynamic elements are written using the Groovy language. Groovy’s syntax is very close to Java’s.

    Dynamic elements are resolved during template execution. The rendered result is then sent as part of the HTTP response.

    Expressions: ${…}

    The simplest way to make a dynamic element is to declare an expression. The syntax used here is${…}. The result of evaluating the expression is inserted in place of the expression.

    For example:

    <h1>Client ${client.name}</h1>
    

    If you can’t be sure of client being null, there is a Groovy shortcut:

    <h1>Client ${client?.name}</h1>
    

    Which will only display the client name if the client is not null.

    Template decorators : #{extends /} and #{doLayout /}

    Decorators provide a clean solution to share a page layout (or design) across several templates.

    Use #{get} and #{set} tags to share variables between the template and the decorator.

    Embedding a page in a decorator is the matter of a one liner:

    #{extends 'simpledesign.html' /}
     
    #{set title:'A decorated page' /}
    This content will be decorated.
    

    The decorator : simpledesign.html

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
      <title>#{get 'title' /}</title>
      <link rel="stylesheet" type="text/css" href="@{'/public/stylesheets/main.css'}" />
    </head>
    <body>
      <h1>#{get 'title' /}</h1>
      #{doLayout /}
      <div class="footer">Built with the play! framework</div>
    </body>
    </html>
    

    Tags: #{tagName /}

    A tag is a template fragment that can be called with parameters. If the tag has only one parameter, by convention it is called “arg” and its name can be omitted.

    For example, this tag inserts a SCRIPT tag to load a JavaScript file:

    #{script 'jquery.js' /}
    

    A tag has to be closed, either directly or by an end tag:

    #{script 'jquery.js' /}
    

    or

    #{script 'jquery.js'}#{/script}
    

    For example the list tag allows iteration over any collection. It takes two mandatory parameters:

    <h1>Client ${client.name}</h1>
    <ul>
        #{list items:client.accounts, as:'account' }
            <li>${account}</li>
        #{/list}
    </ul>
    

    All dynamic expressions are escaped by the template engine to avoid XSS security issues in your application. So the title variable containing <h1>Title</h1> is now escaped:

    ${title} --> &lt;h1&gt;Title&lt;/h1&gt;
    

    If you really want to display it in an unescaped way, you need to explicitely call the raw() method:

    ${title.raw()} --> <h1>Title</h1>
    

    Also, if you want to display a large part of raw HTML, you can use the #{verbatim /} tag:

    #{verbatim}
        ${title} --> <h1>Title</h1>
    #{/verbatim}
    

    Actions: @{…} or @@{…}

    You can use the Router to (reverse) generate a URL corresponding to a specified route. From a template you can use the special @{…} syntax to do that.

    For example:

    <h1>Client ${client.name}</h1>
    <p>
       <a href="@{Clients.showAccounts(client.id)}">All accounts</a>
    </p>
    <hr />
    <a href="@{Clients.index()}">Back</a>
    

    The @@{…} syntax does the same but generates an absolute URL (notably useful for e-mail, …).

    Messages: &{…}

    If your application needs internationalization you can use the &{…} syntax to display an internationalized message:

    For example in the files conf/messages we specify:

    clientName=The client name is %s
    

    To display this message in a template, simply use:

    <h1>&{'clientName', client.name}</h1>
    

    Comment: *{…}*

    Comments aren’t evaluated by the template engine. They are just comments…

    *{**** Display the user name ****}*
    <div class="name">
        ${user.name}
    </div>
    

    Scripts: %{…}%

    A script is a more complicated set of expressions. A script can declare some variables and define some statements. Use the {…} syntax to insert a script.

    %{
       fullName = client.name.toUpperCase()+' '+client.forname;
    }%
     
    <h1>Client ${fullName}</h1>
    

    A script can write dynamic content directly using the out object:

    %{
       fullName = client.name.toUpperCase()+' '+client.forname;
       out.print('<h1>'+fullName+'</h1>');
    }%
    

    You can use a script to create a structure such as an iteration in your template:

    <h1>Client ${client.name}</h1>
    <ul>
    %{
         for(account in client.accounts) { 
    }%
         <li>${account}</li>
    %{
         }
    }%
    </ul>
    

    Bear in mind that a template is not a place to do complex things. So, use a tag when you can, or move the computations into the controller or the model object.

    Template inheritance

    A template can inherit another template, i.e. it can be included as a part of an other template.

    To inherit another template, use the extends tag:

    #{extends 'main.html' /}
     
    <h1>Some code</h1>
    

    The main.html template is a standard template, but it uses the doLayout tag to include the content:

    <h1>Main template</h1>
     
    <div id="content">
        #{doLayout /}
    </div>
    

    Custom template tags

    You can easily create specific tags for your application. A tag is a simple template file, stored in theapp/views/tags directory. The template’s file name is used as the tag name.

    To create a hello tag, just create the app/views/tags/hello.html file.

    Hello from tag!
    

    No need to configure anything. You can use the tag directly:

    #{hello /}
    

    Retrieve tag parameters

    Tag parameters are exposed as template variables. The variable names are constructed with the ‘_’ character prepended to the parameter name.

    For example:

    Hello ${_name} !
    

    And you can pass the name parameter to the tag:

    #{hello name:'Bob' /}
    

    If your tag has only one parameter, you can use the fact than the default parameter name is arg and that its name is implicit.

    Example:

    Hello ${_arg}!
    

    And you can call it easily using:

    #{hello 'Bob' /}
    

    Invoke tag body

    If your tag supports a body, you can include it at any point in the tag code, using the doBody tag.

    For example:

    Hello #{doBody /}!
    

    And you can then pass the name as tag body:

    #{hello}
       Bob
    #{/hello}
    

    Format-specific tags

    You can have different versions of a tag for different content types and Play will select the appropriate tag. For example, Play will use the app/views/tags/hello.html tag when request.format is html, andapp/views/tags/hello.xml when the format is xml.

    Whatever the content type, Play will fall back to the .tag extension if a format-specific tag is not available, e.g. app/views/tags/hello.tag.

    Custom Java tags

    You can also define custom tags in Java code. Similarly to how JavaExtensions work by extending theplay.templates.JavaExtensions class, to create a FastTag you need to create a method in a class that extends play.templates.FastTags. Each method that you want to execute as a tag must have the following method signature.

    public static void _tagName(Map<?, ?> args, Closure body, PrintWriter out, 
       ExecutableTemplate template, int fromLine)
    

    Note the underscore before the tag name.

    To understand how to build an actual tag, let’s look at two of the built-in tags.

    For example, the verbatim tag is implemented by a one-line method that simply calls the toString method on the JavaExtensions, and passes in the body of the tag.

    public static void _verbatim(Map<?, ?> args, Closure body, PrintWriter out, 
       ExecutableTemplate template, int fromLine) {
       
       out.println(JavaExtensions.toString(body));
    }
    

    The body of the tag would be anything between the open and close tag. So

    <verbatim>My verbatim</verbatim>
    

    The body value would be

    My verbatim
    

    The second example is the option tag, which is slightly more complex because it relies on a parent tag to function.

    public static void _option(Map<?, ?> args, Closure body, PrintWriter out, 
          ExecutableTemplate template, int fromLine) {
     
       Object value = args.get("arg");
       Object selection = TagContext.parent("select").data.get("selected");
       boolean selected = selection != null && value != null 
          && selection.equals(value);
     
       out.print("<option value=\"" + (value == null ? "" : value) + "\" " 
          + (selected ? "selected=\"selected\"" : "") 
          + "" + serialize(args, "selected", "value") + ">");
       out.println(JavaExtensions.toString(body));
       out.print("</option>");
    }
    

    This code works by outputting an HTML option tag, and sets the selected value by checking which value is selected from the parent tag. The first three lines set variables for use in the output output. Then, the final three lines output the result of the tag.

    There are many more examples in the source code for the built in tags, with varying degrees of complexity. See FastTags.java in github.

    Tag namespaces

    To ensure that your tags do not conflict between projects, or with the core Play tags, you can set up namespaces, using the class level annotation @FastTags.Namespace.

    So, for a hello tag, in a my.tags namespace, you would do the following

    @FastTags.Namespace("my.tags") 
    public class MyFastTag extends FastTags {
       public static void _hello (Map<?, ?> args, Closure body, PrintWriter out, 
          ExecutableTemplate template, int fromLine) {
          ...
       }
    }
    

    and then in your templates, you would reference the hello tag as

    #{my.tags.hello/}
    

    Java object extensions in templates

    When you use your Java object within the template engine, new methods are added to it. These methods don’t exist in the original Java class and are dynamically added by the template engine.

    For example, to allow easy number formatting in a template, a format method is added tojava.lang.Number.

    It’s then very easy to format a number:

    <ul>
    #{list items:products, as:'product'}
        <li>${product.name}. Price: ${product.price.format('## ###,00')} €</li>
    #{/list}
    </ul>
    

    The same applies to java.util.Date.

    The Java extensions manual page lists the available methods, by type.

    Create custom extensions

    Your project may have specific formatting needs, in which case you can provide your own extensions.

    You only need to create a Java class extending play.templates.JavaExtensions.

    For instance, to provide a custom currency formatter for a number:

    package ext;
     
    import play.templates.JavaExtensions;
     
    public class CurrencyExtensions extends JavaExtensions {
     
      public static String ccyAmount(Number number, String currencySymbol) {
         String format = "'"+currencySymbol + "'#####.##";
         return new DecimalFormat(format).format(number);
      }
     
    }
    

    Each extension method is a static method and should return a java.lang.String to be written back in the page. The first parameter will hold the enhanced object.

    Use your formatter like this:

    <em>Price: ${123456.324234.ccyAmount()}</em>
    

    Template extension classes are automatically detected by Play at start-up. You just have to restart your application to make them available.

    Implicit objects available in a template

    All objects added to the renderArgs scope are directly injected as template variables.

    For instance, to inject a ‘user’ bean into the template from a controller:

    renderArgs.put("user", user );
    

    When you render a template from an action, the framework also adds implicit objects:

    VariableDescriptionAPI documentationSee also
    errors Validation errors play.data.validation.Validation.errors() Validating HTTP data
    flash Flash scope play.mvc.Scope.Flash Controllers - Session & Flash Scope
    lang The current language play.i18n.Lang Setting up I18N - Define languages
    messages The messages map play.i18n.Messages Setting up I18N - Externalize messages
    out The output stream writer java.io.PrintWriter  
    params Current parameters play.mvc.Scope.Params Controllers - HTTP parameters
    play Main framework class play.Play  
    request The current HTTP request play.mvc.Http.Request  
    session Session scope play.mvc.Scope.Session Controllers - Session & Flash Scope

    In addition to the list above the names ownerdelegate and it are reserved in Groovy and shouldn’t be used as variable names in templates.

    Next: Form data validation

    转载于:https://www.cnblogs.com/zhiji6/p/4446788.html

    展开全文
  • Null template engine

    2020-11-22 03:17:49
    m trying to deploy an uber-jar of my Maven project that uses Xdocreport to generate a Docx with Velocity template engine. <p>It's running OK in Eclipse, but when I execute mvn install and java -...
  • Play has an efficient templating system which allows to dynamically generate HTML, XML, JSON or any text-based formatted document... The template engine usesGroovyas an expression language. A tag syst...

    Play has an efficient templating system which allows to dynamically generate HTML, XML, JSON or any text-based formatted document. The template engine uses Groovy as an expression language. A tag system allows you to create reusable functions.

    Templates are stored in the app/views directory.

    Template syntax

    A template file is a text file, some parts of which have placeholders for dynamically generated content. The template’s dynamic elements are written using the Groovy language. Groovy’s syntax is very close to Java’s.

    Dynamic elements are resolved during template execution. The rendered result is then sent as part of the HTTP response.

    Expressions: ${…}

    The simplest way to make a dynamic element is to declare an expression. The syntax used here is${…}. The result of evaluating the expression is inserted in place of the expression.

    For example:

    Client ${client.name}

    If you can’t be sure of client being null, there is a Groovy shortcut:

    Client ${client?.name}

    Which will only display the client name if the client is not null.

    Template decorators : #{extends /} and #{doLayout /}

    Decorators provide a clean solution to share a page layout (or design) across several templates.

    Use #{get} and #{set} tags to share variables between the template and the decorator.

    Embedding a page in a decorator is the matter of a one liner:

    #{extends 'simpledesign.html' /}

    #{set title:'A decorated page' /}

    This content will be decorated.

    The decorator : simpledesign.html

    #{get 'title' /}

    #{get 'title' /}

    #{doLayout /}

    Tags: #{tagName /}

    A tag is a template fragment that can be called with parameters. If the tag has only one parameter, by convention it is called “arg” and its name can be omitted.

    For example, this tag inserts a SCRIPT tag to load a JavaScript file:

    #{script 'jquery.js' /}

    A tag has to be closed, either directly or by an end tag:

    #{script 'jquery.js' /}

    or

    #{script 'jquery.js'}#{/script}

    For example the list tag allows iteration over any collection. It takes two mandatory parameters:

    Client ${client.name}

    #{list items:client.accounts, as:'account' }

    ${account}

    #{/list}

    All dynamic expressions are escaped by the template engine to avoid XSS security issues in your application. So the title variable containing 

    Title

     is now escaped:

    ${title} --> <h1>Title</h1>

    If you really want to display it in an unescaped way, you need to explicitely call the raw() method:

    ${title.raw()} -->

    Title

    Also, if you want to display a large part of raw HTML, you can use the #{verbatim /} tag:

    #{verbatim}

    ${title} -->

    Title

    #{/verbatim}

    Actions: @{…} or @@{…}

    You can use the Router to (reverse) generate a URL corresponding to a specified route. From a template you can use the special @{…} syntax to do that.

    For example:

    Client ${client.name}

    All accounts


    Back

    The @@{…} syntax does the same but generates an absolute URL (notably useful for e-mail, …).

    Messages: &{…}

    If your application needs internationalization you can use the &{…} syntax to display an internationalized message:

    For example in the files conf/messages we specify:

    clientName=The client name is %s

    To display this message in a template, simply use:

    &{'clientName', client.name}

    Comment: *{…}*

    Comments aren’t evaluated by the template engine. They are just comments…

    *{**** Display the user name ****}*

    ${user.name}

    Scripts: %{…}%

    A script is a more complicated set of expressions. A script can declare some variables and define some statements. Use the {…} syntax to insert a script.

    %{

    fullName = client.name.toUpperCase()+' '+client.forname;

    }%

    Client ${fullName}

    A script can write dynamic content directly using the out object:

    %{

    fullName = client.name.toUpperCase()+' '+client.forname;

    out.print('

    '+fullName+'

    ');

    }%

    You can use a script to create a structure such as an iteration in your template:

    Client ${client.name}

    %{

    for(account in client.accounts) {

    }%

    ${account}

    %{

    }

    }%

    Bear in mind that a template is not a place to do complex things. So, use a tag when you can, or move the computations into the controller or the model object.

    Template inheritance

    A template can inherit another template, i.e. it can be included as a part of an other template.

    To inherit another template, use the extends tag:

    #{extends 'main.html' /}

    Some code

    The main.html template is a standard template, but it uses the doLayout tag to include the content:

    Main template

    #{doLayout /}

    Custom template tags

    You can easily create specific tags for your application. A tag is a simple template file, stored in theapp/views/tags directory. The template’s file name is used as the tag name.

    To create a hello tag, just create the app/views/tags/hello.html file.

    Hello from tag!

    No need to configure anything. You can use the tag directly:

    #{hello /}

    Retrieve tag parameters

    Tag parameters are exposed as template variables. The variable names are constructed with the ‘_’ character prepended to the parameter name.

    For example:

    Hello ${_name} !

    And you can pass the name parameter to the tag:

    #{hello name:'Bob' /}

    If your tag has only one parameter, you can use the fact than the default parameter name is arg and that its name is implicit.

    Example:

    Hello ${_arg}!

    And you can call it easily using:

    #{hello 'Bob' /}

    Invoke tag body

    If your tag supports a body, you can include it at any point in the tag code, using the doBody tag.

    For example:

    Hello #{doBody /}!

    And you can then pass the name as tag body:

    #{hello}

    Bob

    #{/hello}

    Format-specific tags

    You can have different versions of a tag for different content types and Play will select the appropriate tag. For example, Play will use the app/views/tags/hello.html tag when request.format is html, andapp/views/tags/hello.xml when the format is xml.

    Whatever the content type, Play will fall back to the .tag extension if a format-specific tag is not available, e.g. app/views/tags/hello.tag.

    Custom Java tags

    You can also define custom tags in Java code. Similarly to how JavaExtensions work by extending theplay.templates.JavaExtensions class, to create a FastTag you need to create a method in a class that extends play.templates.FastTags. Each method that you want to execute as a tag must have the following method signature.

    public static void _tagName(Map, ?> args, Closure body, PrintWriter out,

    ExecutableTemplate template, int fromLine)

    Note the underscore before the tag name.

    To understand how to build an actual tag, let’s look at two of the built-in tags.

    For example, the verbatim tag is implemented by a one-line method that simply calls the toString method on the JavaExtensions, and passes in the body of the tag.

    public static void _verbatim(Map, ?> args, Closure body, PrintWriter out,

    ExecutableTemplate template, int fromLine) {

    out.println(JavaExtensions.toString(body));

    }

    The body of the tag would be anything between the open and close tag. So

    My verbatim

    The body value would be

    My verbatim

    The second example is the option tag, which is slightly more complex because it relies on a parent tag to function.

    public static void _option(Map, ?> args, Closure body, PrintWriter out,

    ExecutableTemplate template, int fromLine) {

    Object value = args.get("arg");

    Object selection = TagContext.parent("select").data.get("selected");

    boolean selected = selection != null && value != null

    && selection.equals(value);

    out.print("

    + (selected ? "selected=\"selected\"" : "")

    + "" + serialize(args, "selected", "value") + ">");

    out.println(JavaExtensions.toString(body));

    out.print("

    ");

    }

    This code works by outputting an HTML option tag, and sets the selected value by checking which value is selected from the parent tag. The first three lines set variables for use in the output output. Then, the final three lines output the result of the tag.

    There are many more examples in the source code for the built in tags, with varying degrees of complexity. See FastTags.java in github.

    Tag namespaces

    To ensure that your tags do not conflict between projects, or with the core Play tags, you can set up namespaces, using the class level annotation @FastTags.Namespace.

    So, for a hello tag, in a my.tags namespace, you would do the following

    @FastTags.Namespace("my.tags")

    public class MyFastTag extends FastTags {

    public static void _hello (Map, ?> args, Closure body, PrintWriter out,

    ExecutableTemplate template, int fromLine) {

    ...

    }

    }

    and then in your templates, you would reference the hello tag as

    #{my.tags.hello/}

    Java object extensions in templates

    When you use your Java object within the template engine, new methods are added to it. These methods don’t exist in the original Java class and are dynamically added by the template engine.

    For example, to allow easy number formatting in a template, a format method is added tojava.lang.Number.

    It’s then very easy to format a number:

    #{list items:products, as:'product'}

    ${product.name}. Price: ${product.price.format('## ###,00')} €

    #{/list}

    The same applies to java.util.Date.

    The Java extensions manual page lists the available methods, by type.

    Create custom extensions

    Your project may have specific formatting needs, in which case you can provide your own extensions.

    You only need to create a Java class extending play.templates.JavaExtensions.

    For instance, to provide a custom currency formatter for a number:

    package ext;

    import play.templates.JavaExtensions;

    public class CurrencyExtensions extends JavaExtensions {

    public static String ccyAmount(Number number, String currencySymbol) {

    String format = "'"+currencySymbol + "'#####.##";

    return new DecimalFormat(format).format(number);

    }

    }

    Each extension method is a static method and should return a java.lang.String to be written back in the page. The first parameter will hold the enhanced object.

    Use your formatter like this:

    Price: ${123456.324234.ccyAmount()}

    Template extension classes are automatically detected by Play at start-up. You just have to restart your application to make them available.

    Implicit objects available in a template

    All objects added to the renderArgs scope are directly injected as template variables.

    For instance, to inject a ‘user’ bean into the template from a controller:

    renderArgs.put("user", user );

    When you render a template from an action, the framework also adds implicit objects:

    In addition to the list above the names owner, delegate and it are reserved in Groovy and shouldn’t be used as variable names in templates.

    展开全文
  • Null template engine. Set template engine with IXDocReport#setTemplateEngine. fr.opensagres.xdocreport.core.XDocReportException: Null template engine. Set template engine with IXDocReport#...
  • <p>With the current state of <em>develop</em> the former syntax will throw an exception because of the unbound template engine for <code>text/plain</code>.</p><p>该提问来源于开源项目:...
  • <p>https://github.com/vert-x3/vertx-web/blob/master/vertx-template-engines/vertx-web-templ-pebble/pom.xml#L19</p> <p>the current version is 3.0.8</p><p>该提问来源于开源项目:vert-x3/vertx-web...
  • Play的Template Engine (1)

    2009-11-16 10:15:02
    Play 有一套高效的模版系统,它可以由有格式的文本来动态...它的Template Engine使用Groovy作为表达式语言。 以下举几个例子: 1.Expressions : ${…} Client ${client.name} 2.Tags : #{tagName /} ...
    Play 有一套高效的模版系统,它可以由有格式的文本来动态的生成Html,Xml,JSON或者其他文本。它的Template Engine使用Groovy作为表达式语言。
    以下举几个例子:
    1.Expressions : ${…}

    <h1>Client ${client.name}</h1>

    2.Tags : #{tagName /}

    #{script 'jquery.js' /}
    也可以写成:
    #{script 'jquery.js'}#{/script}

    迭代标签:
    <h1>Client ${client.name}</h1>
    <ul>
    #{list items:client.accounts, as:'account' }
    <li>${account}</li>
    #{/list}
    </ul>

    3.Actions : @{…} or @@{…}
    使用Router 来把URL转换成相当应的route,@{…} 这个标签就可以完成
    这个功能。
    <h1>Client ${client.name}</h1>
    <p>
    <a href="@{Clients.showAccounts(client.id)}">All accounts</a>
    </p>
    <hr />
    <a href="@{Clients.index()}">Back</a>

    @@{…}用法一样而且可以生成绝对路径(尤其是有用的Emial)


    4.Messages : &{…}
    国际化标签, 在conf下建message文件.
    写下:clientName=The client name is %s
    使用:<h1>&{'clientName', client.name}</h1>


    5.Comment : *{…}*
    注释标签: *{**** Display the user name ****}*


    6.Scripts : %{…}%
    脚本标签: 脚本是一个更为复杂的表达式,可以用来定义一些变量和语句。
    %{
    fullName = client.name.toUpperCase()+' '+client.forname;
    }%
    <h1>Client ${fullName}</h1>

    脚本可以直接使用out对象写动态的内容:
    %{
    fullName = client.name.toUpperCase()+' '+client.forname;
    out.print('<h1>'+fullName+'</h1>');
    }%

    你也可以在你的模版里使用脚本创建譬如iteration的结构:
    <h1>Client ${client.name}</h1>
    <ul>
    %{
    for(account in client.accounts) {
    }%
    <li>${account}</li>
    %{
    }
    }%
    </ul>
    展开全文
  • <div><p>Thymeleaf 3.0 builds around a <strong>completely new template processing engine, codenamed <em>aurora, developed with the aim of improving its execution performance and reducing its memory ...
  • <div><p>When trying to ...<p>My template looks like this: <pre><code> xml <?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0" xmlns:atom="...
  • <div><p>If the mime_type of the ActionView::Template being rendered is <code>text/xml</code> then a format of <code>:xhtml</code> will be used even if the global output format is set to <code>:...
  • I classified this as a bug because I thought that this would be abstracted away by the provisioning engine, but feel free to correct this thinking if I didn't get it right. <h4>Category [x] Bug ...
  • velocity+xml解析的sql模板引擎,让复杂多条件的sql编写更简单、更快速 ???? 使用案例 在spring boot项目的resource目录下新建一个jpql文件夹,并在jpql文件夹下新建一个xml文件用来写sql语句。比如,这里我...

    🚀 复杂多条件SQL语句模板引擎

    velocity+xml解析的sql模板引擎,让复杂多条件的sql编写更简单、更快速

    🐼 使用案例

    1. 在spring boot项目的resource目录下新建一个jpql文件夹,并在jpql文件夹下新建一个xml文件用来写sql语句。比如,这里我新建一个TestJpql.xml,目录结构如下:
    ...
    --> resource
       --> jpql
           --> TestJpql.xml
    ...
    
    1. TestJpql.xml中编写sql语句。举个例子:
    <?xml version="1.0" encoding="UTF-8" ?>
    <jpa module="testJpql">
        <jpql id="customSQL">
            select * from so_tag where 1=1
            #if($title)
            and title like :title
            #end
            #if($readCount)
            and read_count &gt; :readCount
            #end
            #if($tagNames)
            and tag_name in (:tagNames)
            #end
            limit 10
        </jpql>
        <jpql id="xxx">
            ...
        </jpql>
        ...
    </jpa>
    

    这里解释下编写的语法:

    • xml标签基本固定,主要用来定位每个jpql标签中的sql语句。
      • jpa标签中的module属性是这个xml文件的id,不同的文件通过这个属性做区分;
      • jpql标签中的id属性用于标识一个xml文件中不同的sql语句;
    • jpql标签中的sql语句语法参考velocity模板引擎
    1. 在代码中使用。此处在Test中通过hibernate框架执行解析后的sql:
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Slf4j
    public class ServiceTest {
    
        @Autowired
        JpqlParser jpqlParser;
        @Autowired
        private EntityManagerFactory entityManagerFactory;
    
        public Session getSession() {
            return entityManagerFactory.unwrap(SessionFactory.class).openSession();
        }
    
        @Test
        public void test1() {
            Map<String, Object> parameters = new HashMap<>(4);
    //        parameters.put("title", "%原则%");
    //        parameters.put("readCount", 400);
            parameters.put("tagNames", Arrays.asList("平台", "后台"));
            String sql = jpqlParser.parse(new ParserParameter("testJpql.customSQL", parameters, "mysql")).getExecutableSql();
            Query query = getSession().createNativeQuery(sql).addEntity(TagEntity.class);
            List<TagEntity> result = query.getResultList();
            System.out.println("结果返回个数:" + result.size());
        }
    }
    

    输出如下:

    2020-01-19 17:48:46.890  INFO 16228 --- [main] com.sleepy.jpql.ParsedJpql: {"QueryId": "customSQL","SQL": "select * from so_tag where 1=1 and tag_name in ('平台','后台') limit 10"}
    结果返回个数:10
    

    这里的parameters中的每个元素对应的就是jpql标签sql语句中的变量。通过so-jpql-template-engine框架,你可以获取到解析后的sql语句,然后可以通过ORM框架或原生JDBC去执行获取查询结果。免去了类似sql需要手动重复拼接的麻烦,通过一条sql模板即可搞定。😜

    ☀️ 使用步骤

    1. 下载本项目到本地
    git clone git@github.com:SleepyOcean/so-jpql-template-engine.git
    
    1. 将项目安装到本地maven仓库
    mvn clean install
    
    1. 在自己的maven项目中的pom.xml中引入依赖
    <dependencies>
           ... ...
           <dependency>
               <groupId>com.sleepy</groupId>
               <artifactId>so-jpql-template-engine</artifactId>
               <version>1.0.0</version>
           </dependency>
           ... ...
    </dependencies>
    
    1. 在自己的spring boot启动类中的包扫描注解中加入com.sleepy.jpql包名
    @SpringBootApplication(scanBasePackages = {"com.sleepy.blog", "com.sleepy.jpql"})
    ...
    public class SoBlogServiceApplication extends SpringBootServletInitializer {
       ...
    }
    
    1. 剩下的就是上述案例的内容啦~

    🏃 未完待续

    本项目刚刚提交,还未发布到Maven中央仓库,后续会发布到中央仓库,简化依赖引入

    💙 版权说明

    该项目签署了Apache-2.0授权许可,详情请参阅 LICENSE.md

    项目地址: So Jpql Template Engine

    展开全文
  • 适合于所有通过文本模板生成文本类型内容的场景,如:XML、源文件、HTML等等,可以说,它的出现就是为了替换Velocity模板引擎而来,因此在指令集上在尽量与Velocity接近的同时,又扩展了一些Velocity不能很好解决...
  • <p><code>[11-Mar-2019 16:45:56 UTC] PHP Fatal error: Method Magento\Ui\TemplateEngine\Xhtml\Result::__toString() must not throw an exception, caught Error: Call to a member function ...
  • Play有一个高效的用来动态生成HTML, XML, JSON, 任何文本格式文档的模板系统。模板引擎使用Groovy(一种JVM平台上的动态语言)作为表达式语言。包含一个可以用来创建可重用函数的标签系统。 模板保存在app/views...
  • 这是《PHP in Action》书中着重提到的一个作者最喜欢的PHP引擎,他是基于模板属性语言(template attribute language)的引擎,他是用XML属性而不是像smaty这种用特殊的标记(如{})来写模板的。 smaty的写法: ...
  • click to quickly deploy a file (rather than all items in the XML file) and right-click to quickly deploy the entire provisioning template. The PnP provisioning engine XML file is fully supported (ie: ...
  • <div><p>After the release of the site provision engine with the remote provisioning xml support, we should be looking into providing "save site as a template" capability to extract existing ...
  • xml view problems

    2021-01-09 13:56:45
    DEBUG - TEMPLATE (0.0016ms) /service1/parse.xml NoMethodError - undefined method `to_xml' for {:url=>"123"}:Hash: /usr/local/rvm/gems/ruby-1.9.3-p194/gems/rabl-0.6.13/lib/rabl/...
  • at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)...
  • ve extracted a Provisioning Template XML from an existing site (in this case using PowerShell Get-SPOProvisioningTemplate). I then applied this template to another site. After applying this template I...
  • load could not load template

    2020-12-09 13:55:54
    return self._read_template(self.get_view_id(xml_id)) File "", line 2, in _read_template File "/usr/lib/python3/dist-packages/odoo/tools/cache.py", line 86, in lookup key = key0 ...
  • Thymeleaf:面向Java的XML/HTML模板引擎

    千次阅读 2011-08-15 22:29:56
    本文来源于我在InfoQ中文站翻译的文章,原文地址是:http://www.infoq.com/cn/news/2011/08/thymeleaf-1.0.0-template-engine Thymeleaf的首个稳定版(1.0.0版)已经于上月17日发布了。Thymelea

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 419
精华内容 167
关键字:

enginetemplatexml