php - 有没有办法在 Mustache 模板中包含 mysql 查询?

标签 php mysql mustache mustache.php

我正在尝试将 mysql 查询中的值设置为 Mustache 中的模板。 我正在使用mustache.php是否有可能做到这一点?我找不到任何有关模板查询的文档。有没有人有更好的解决方案?

    <?php
/*
 * PHP Mustache - Basic Mustache example in PHP
 */
$servername = "localhost";
$database = "laravel";
$username = "root";
$password = "root";

try {

    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception

} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

$query = $conn->query('SELECT * FROM users');

//register mustache library
require 'Mustache/Autoloader.php';
Mustache_Autoloader::register();


//set the template string (obviously complex application will use files)
$template = 'Hello, {{name}},<br /> Your last name is {{lastname}}';


//set the template values
$values = array(
    $query = $conn->query('SELECT * FROM users');
    'name' = $row['name'];
    'lastname' = $row['lastname'];
);


//start the mustache engine
$m = new Mustache_Engine;

//render the template with the set values
echo $row['name'];
echo $row['lastname'];
echo $m->render($template, $values);
?>

最佳答案

试试这样

$statement = $conn->query('SELECT * FROM users');
$row = $statement->fetch(PDO::FETCH_ASSOC);

//start the mustache engine
$m = new Mustache_Engine;
echo $m->render($template, $row);

关于php - 有没有办法在 Mustache 模板中包含 mysql 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28453982/

相关文章:

mysql - 如何解决在亚马逊托管 jboss Web 应用程序时数据库连接被拒绝的问题

php - 加载页面时未定义索引

mysql - CakePHP 用户登录功能

javascript - 如何在 mustache 中呈现数组的一个元素

node.js - 将 mustache.js 与 node.js 一起使用?

php - Laravel - 尝试获取非对象形式错误的属性

php - PDO 数据库实例返回 null

php - 自定义验证消息不起作用?

javascript - mustache :仅检查当前上下文中的变量

javascript - 使用AJAX和PHP更改onclick