Skip to content

Commit

Permalink
πŸ› Fix optional chaining not working in EJS code, fixes #15
Browse files Browse the repository at this point in the history
  • Loading branch information
skerit committed Feb 15, 2024
1 parent 3331801 commit 357d623
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 2.3.17 (WIP)

* Fix optional chaining not working in EJS code

## 2.3.16 (2024-02-15)

* Trigger `HePlaceholder` render when made & inserted in the DOM manually
Expand Down
6 changes: 4 additions & 2 deletions lib/core/hawkejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,8 @@ Main.setMethod(function parseTemplateSyntax(source, name, wrap_ejs) {
*/
Main.setMethod(function rewriteVariableReferences(code, scopes, level) {

var result = '',
let prev_value,
result = '',
tokens = Fn.tokenize(code, true),
token,
next,
Expand Down Expand Up @@ -975,7 +976,7 @@ Main.setMethod(function rewriteVariableReferences(code, scopes, level) {
if (token.type == 'name') {

// We don't modify property names
if (!prev || (prev && prev.value != '.')) {
if (prev_value != '.' && prev_value != '?.') {
if (next && next.type == 'punct' && next.value == ':') {
// Skip key names in object literals
continue;
Expand Down Expand Up @@ -1015,6 +1016,7 @@ Main.setMethod(function rewriteVariableReferences(code, scopes, level) {
}

prev = token;
prev_value = token.value;
}

for (i = 0; i < tokens.length; i++) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "hawkejs",
"description": "Asynchronous Embedded JavaScript templates",
"version": "2.3.16",
"version": "2.3.17-alpha",
"author": "Jelle De Loecker <[email protected]>",
"keywords": [
"template",
Expand Down
25 changes: 25 additions & 0 deletions test/10-expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,30 @@ This should be a converted variable:

});

describe('EJS', function() {

let tests = [
[
`<% if (bla?.bla?.bla) { %>BLA<% } else { %>NO BLA<% } %>`,
`NO BLA`
],
[
`<%= test?.two?.three?.four %>`,
`4`
],
[
`<%= test?.two?.doesnotexist ?? my_obj?.a %>`,
`a`
],
[
`<%= is_null ?? my_obj?.a %>`,
`a`
],
];

createTests(tests);
});

return;

describe('None existing method calls', function() {
Expand Down Expand Up @@ -871,6 +895,7 @@ function createTests(tests) {
__test : {nested: {value: 'test'}},
c : 'c',
str_bla : 'bla',
is_null : null,
empty_arr : [],
full_arr : [0],
single : [0],
Expand Down

0 comments on commit 357d623

Please sign in to comment.