diff --git a/vlib/v/parser/tmpl.v b/vlib/v/parser/tmpl.v
index a0cb5e3ca5..a6992f4d20 100644
--- a/vlib/v/parser/tmpl.v
+++ b/vlib/v/parser/tmpl.v
@@ -214,11 +214,15 @@ mut sb := strings.new_builder($lstartlength)\n
} else {
source.writeln('')
}
+ } else if state == .js {
+ // replace `$` to `\$` at first to escape JavaScript template literal syntax
+ source.writeln(line.replace(r'$', r'\$').replace(r'$$', r'@').replace(r'.$',
+ r'.@').replace(r"'", r"\'"))
} else {
// HTML, may include `@var`
// escaped by cgen, unless it's a `vweb.RawHtml` string
- source.writeln(line.replace('@', '$').replace('$$', '@').replace('.$', '.@').replace("'",
- "\\'"))
+ source.writeln(line.replace(r'@', r'$').replace(r'$$', r'@').replace(r'.$',
+ r'.@').replace(r"'", r"\'"))
}
}
source.writeln(parser.tmpl_str_end)
diff --git a/vlib/v/tests/inout/file.html b/vlib/v/tests/inout/file.html
index e06ad8c411..4e15416c55 100644
--- a/vlib/v/tests/inout/file.html
+++ b/vlib/v/tests/inout/file.html
@@ -17,6 +17,9 @@ color: red;
diff --git a/vlib/v/tests/inout/tmpl_parse_html.out b/vlib/v/tests/inout/tmpl_parse_html.out
index c855f16616..d8928fa999 100644
--- a/vlib/v/tests/inout/tmpl_parse_html.out
+++ b/vlib/v/tests/inout/tmpl_parse_html.out
@@ -17,6 +17,9 @@ color: red;