Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support 'is not _' expression syntax #265

Open
tjsmith-meta opened this issue Sep 25, 2024 · 0 comments
Open

Support 'is not _' expression syntax #265

tjsmith-meta opened this issue Sep 25, 2024 · 0 comments

Comments

@tjsmith-meta
Copy link

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant