search
HomePHP FrameworkThinkPHPHow to obtain template variables in JS in TP (detailed example)

The following thinkphp frameworkThe tutorial column will introduce to you the elegant way to obtain template variables through JS in the PHP framework. I hope it will be helpful to friends in need!

When using the PHP framework (this article uses ThinkPHP as an example) for page development, we often encounter When it is necessary to substitute the template variables in the controller method into the page JS for operation, the common method is:

  let admin={:json_encode($admin)},  //$admin是php数组
      level={$level};  
  console.log(admin, level);

This method can indeed get the value, but there are a few problems

  • The syntax of template variables is placed in js, and the editor will report a syntax error
  • When the editor's automatic formatting function is used, the declaration structure of the template variables will be destroyed, thus affecting the The use of the automatic formatting code function
  • is not beautiful enough

In practice, the more recommended way is:Save template variables to specific nodes, and then use global methods Convert them into global variables. Finally, you need to use the methods of these variables to read these global variables. Take a complete template as an example below:

<!DOCTYPE html>  
<html lang ="en">  
<head>  
 <meta charset="UTF-8">  
 <title>PHP框架中JS优雅获取模板变量的方式</title>  
 <style>  
 /* 通用的模板数据存放标签,视觉不可见 */  
 .data-box {  
      display: none;  
  }  
 </style>  
</head>  
<body>  
<!-- 页面内容 -->  
<h2 id="Hi-结果请看console">Hi,结果请看console</h2>
  
<!-- 数据存储节点,可以同时存在多个data属性 -->  
<!-- 如果模板变量是数组,须先转成json字符串(如$admin) -->  
<div class="data-box" data-admin=&#39;{:json_encode($admin)}&#39; data-level=&#39;{$level}&#39;></div>  
  
  
<script>  
  /* 获取数据的操作 */  
  
 /* 初始化页面渲染时传过来的js变量 */  
 let dataContainerElem = document.querySelector(&#39;.data-box&#39;),  
     data = dataContainerElem ? dataContainerElem.dataset : {},  
     dataBox = {}; //模板变量容器,`.data-box`类选择器所在的所有`data`属性值集合  
  
  Object.keys(data).forEach(function (key) {  
      dataBox[key] = data[key];  
      if (isJsonString(data[key])) dataBox[key] = JSON.parse(data[key]); //是json格式的字串才转对象  
  });  
  
 /**  
  * 判断字串是否属于json字串  
  */  
 function isJsonString(str) {  
     let flag = false;  
  
     if (typeof str != &#39;string&#39;) return flag;  
  
     try {  
         JSON.parse(str);  
         flag = true;  
     } catch (e) {}  
  
     return flag;  
  }  
</script>  
  
<script>  
  /* 使用数据 */  
 //所有保存到数据节点的变量都成为`dataBox`对象的属性  
  console.log(dataBox.admin, dataBox.level);  
</script>  
</body>  
</html>

In actual development, I will place the css here and the js operation for obtaining data in the global mother template, and then the specific sub-templates only need to inherit the mother template You can use this function to facilitate code reuse.

Recommended: "The latest 10 thinkphp video tutorials"

The above is the detailed content of How to obtain template variables in JS in TP (detailed example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),