# 12.3 JavaScript内联

JavaScript内联考虑了更好地整合`HTML`模版模式下的JavaScript `<script>`块。

与文本内联一样，这实际上等价于在`JAVASCRIPT`模版模式下处理脚本内容。因此，文本模版模式（看下一章）的所有能力也就触手可及了。但是，这一节我们将聚焦在如何使用它来将Thymeleaf表达式的输出添加到JavaScript块里。

JavaScript内联需要使用`th:inline="javascript"`显式启用：

```markup
<script th:inline="javascript">
    ...
    var username = [[${session.user.name}]];
    ...
</script>
```

这会生成：

```markup
<script th:inline="javascript">
    ...
    var username = "Sebastian \"Fruity\" Applejuice";
    ...
</script>
```

上面的代码里有两件重要的事情需要提醒一下：

首先，JavaScript内联不仅仅会输出需要的文本，而且会用引号将它括起来，并转义内容。这样，表达式的结果会以`格式良好的JavaScript字面量`输出。

其次，会这样是因为我们以`转义`的方式输出了`${session.user.name}`表达式。即使用双括号表达式：`[[${session.user.name}]]`。如果我们使用非转义的方式，例如：

```markup
<script th:inline="javascript">
    ...
    var username = [(${session.user.name})];
    ...
</script>
```

结果会是这样：

```markup
<script th:inline="javascript">
    ...
    var username = Sebastian "Fruity" Applejuice;
    ...
</script>
```

这是畸形的JavaScript代码。但是如果我们正在用追加内联表达式的方式构建部分脚本，输出非转义的东西可能正是我们需要的。所以，手边有这个工具还是很赞的。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/thymeleaf/i.-using-thymeleaf/12-nei-lian/12.3-javascript-inlining.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
