Search in sources :

Example 1 with ConditionalExpressionBuilder

use of com.google.template.soy.jssrc.dsl.ConditionalExpressionBuilder in project closure-templates by google.

the class GenJsExprsVisitor method visitIfNode.

/**
 * Example:
 * <pre>
 *   {if $boo}
 *     AAA
 *   {elseif $foo}
 *     BBB
 *   {else}
 *     CCC
 *   {/if}
 * </pre>
 * might generate
 * <pre>
 *   (opt_data.boo) ? AAA : (opt_data.foo) ? BBB : CCC
 * </pre>
 */
@Override
protected void visitIfNode(IfNode node) {
    // Create another instance of this visitor class for generating JS expressions from children.
    GenJsExprsVisitor genJsExprsVisitor = genJsExprsVisitorFactory.create(translationContext, templateAliases, errorReporter);
    CodeChunk.Generator generator = translationContext.codeGenerator();
    List<CodeChunk.WithValue> ifs = new ArrayList<>();
    List<CodeChunk.WithValue> thens = new ArrayList<>();
    CodeChunk.WithValue trailingElse = null;
    for (SoyNode child : node.getChildren()) {
        if (child instanceof IfCondNode) {
            IfCondNode ifCond = (IfCondNode) child;
            ifs.add(translateExpr(ifCond.getExpr()));
            thens.add(CodeChunkUtils.concatChunks(genJsExprsVisitor.exec(ifCond)));
        } else if (child instanceof IfElseNode) {
            trailingElse = CodeChunkUtils.concatChunks(genJsExprsVisitor.exec(child));
        } else {
            throw new AssertionError();
        }
    }
    Preconditions.checkState(ifs.size() == thens.size());
    ConditionalExpressionBuilder builder = CodeChunk.ifExpression(ifs.get(0), thens.get(0));
    for (int i = 1; i < ifs.size(); i++) {
        builder.elseif_(ifs.get(i), thens.get(i));
    }
    CodeChunk.WithValue ifChunk = trailingElse != null ? builder.else_(trailingElse).build(generator) : builder.else_(LITERAL_EMPTY_STRING).build(generator);
    chunks.add(ifChunk);
}
Also used : IfElseNode(com.google.template.soy.soytree.IfElseNode) SoyNode(com.google.template.soy.soytree.SoyNode) ParentSoyNode(com.google.template.soy.soytree.SoyNode.ParentSoyNode) WithValue(com.google.template.soy.jssrc.dsl.CodeChunk.WithValue) ConditionalExpressionBuilder(com.google.template.soy.jssrc.dsl.ConditionalExpressionBuilder) ArrayList(java.util.ArrayList) IfCondNode(com.google.template.soy.soytree.IfCondNode) CodeChunk(com.google.template.soy.jssrc.dsl.CodeChunk) WithValue(com.google.template.soy.jssrc.dsl.CodeChunk.WithValue)

Aggregations

CodeChunk (com.google.template.soy.jssrc.dsl.CodeChunk)1 WithValue (com.google.template.soy.jssrc.dsl.CodeChunk.WithValue)1 ConditionalExpressionBuilder (com.google.template.soy.jssrc.dsl.ConditionalExpressionBuilder)1 IfCondNode (com.google.template.soy.soytree.IfCondNode)1 IfElseNode (com.google.template.soy.soytree.IfElseNode)1 SoyNode (com.google.template.soy.soytree.SoyNode)1 ParentSoyNode (com.google.template.soy.soytree.SoyNode.ParentSoyNode)1 ArrayList (java.util.ArrayList)1