Spring Boot中Thymeleaf动态赋值求助:HTML模板传参问题
Looks like you're working with Spring and Thymeleaf to dynamically inject values into your HTML template—great choice for server-side rendering! Let's walk through getting this fully working.
Step 1: Complete Thymeleaf Template
First, your HTML template is set up correctly with Thymeleaf attributes. Here's the full version for clarity:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title th:text="${title}"></title> </head> <body> <div class="page-content"> <h1 th:text="|Hello ${siteCode}!|"></h1> </div> </body> </html>
Key details here:
th:text="${title}"replaces the<title>content with thetitlevalue from your model.- The literal substitution syntax
|Hello ${siteCode}!|lets you mix static text with dynamic variables cleanly, which is far cleaner than manual string concatenation.
Step 2: Populate the Spring Model Correctly
Your Java code was cut off, but you just need to add the missing siteCode attribute to the model. Here's the complete, working version:
// Create the model instance Model model = new ExtendedModelMap(); // Add the title value (assuming 'site' is your domain object) model.addAttribute("title", site.getName()); // Add the siteCode value to match the template's variable model.addAttribute("siteCode", site.getCode()); // Replace with your actual site code getter method
Critical checks:
- Ensure variable names in
model.addAttribute()exactly match the ones in your Thymeleaf template (titleandsiteCode—they’re case-sensitive!). - Confirm your
siteobject has valid getter methods (likegetName()andgetCode()) to retrieve the values you need.
Step 3: Render the Template (Controller Example)
To tie it all together, here’s how you’d use this model in a Spring Controller to render the template:
@Controller public class SiteController { @GetMapping("/greeting") public String getGreeting(Model model) { // Fetch your site object from a service/database (example hardcoded here) Site site = new Site("My Awesome Site", "AWESOME123"); model.addAttribute("title", site.getName()); model.addAttribute("siteCode", site.getCode()); // Return the name of your Thymeleaf template (omit .html extension) return "greeting"; } }
When you visit /greeting, Thymeleaf will render the template with your dynamic values:
- The page title will show "My Awesome Site"
- The
<h1>will display "Hello AWESOME123!"
Common Pitfalls to Avoid
- Typos: A small mismatch between model variable names and template variables will break the dynamic rendering. Double-check spelling and case.
- Null Values: Add fallbacks if your
siteobject or its properties might be null (e.g.,th:text="${title ?: 'Default Site Title'}"). - Missing Dependencies: Make sure your project includes the Spring Boot Thymeleaf starter (or equivalent dependencies) in your build file—otherwise Thymeleaf won’t process your template.
内容的提问来源于stack exchange,提问作者Anandu Mohan

