Skip to content

Support 'is not _' expression syntax #265

Description

@tjsmith-meta

Here's the example template that works in Python jinja2 -- 'is not defined'.

{% if foo is not defined %}
not defined
{% endif %}
{% set foo = False %}
{% if foo is not defined %}
  {% set foo = True %}
{% endif %}
{{ foo }}

I realize there is an 'undefined' operator which is already supported, but 'not defined' appears to be a valid formulation as well.

Here's the change I have for reference that seems to do the trick for me.

diff --git a/jinja2cpp/src/expression_parser.cpp b/jinja2cpp/src/expression_parser.cpp
--- a/jinja2cpp/src/expression_parser.cpp
+++ b/jinja2cpp/src/expression_parser.cpp
@@ -151,7 +151,14 @@
             break;
         case Keyword::Is:
         {
+            bool wrapWithNot = false;
+
             Token nextTok = lexer.NextToken();
+            if (lexer.GetAsKeyword(nextTok) == Keyword::LogicalNot) {
+              wrapWithNot = true;
+              nextTok = lexer.NextToken();
+            }
+
             if (nextTok != Token::Identifier)
                 return MakeParseError(ErrorCode::ExpectedIdentifier, nextTok);

@@ -164,7 +171,12 @@
             if (!params)
                 return params.get_unexpected();

-            return std::make_shared<IsExpression>(*left, std::move(name), std::move(*params));
+            auto isExpr = std::make_shared<IsExpression>(*left, std::move(name), std::move(*params));
+            if (wrapWithNot) {
+              return std::make_shared<UnaryExpression>(UnaryExpression::Operation::LogicalNot, isExpr);
+            } else {
+              return isExpr;
+            }
         }
         default:
             lexer.ReturnToken();

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions