¿Cómo puedo hacer que Express emita HTML con un buen formato?


Cuando se usa Express for Node.js, me di cuenta de que produce el código HTML sin ningún carácter de nueva línea o pestañas. Aunque puede ser más eficiente para descargar, no es muy legible durante el desarrollo.

¿Cómo puedo hacer que Express emita HTML con un buen formato?

Author: Stephen, 2011-03-11

9 answers

En su principal app.js o lo que está en su lugar:

Express 4.x

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

Express 3.x

app.configure('development', function(){
  app.use(express.errorHandler());
  app.locals.pretty = true;
});

Express 2.x

app.configure('development', function(){
  app.use(express.errorHandler());
  app.set('view options', { pretty: true });
});

Puse la impresión bonita en development porque querrás más eficiencia con la 'fea' en production. Asegúrese de establecer la variable de entorno NODE_ENV=production cuando esté implementando en producción. Esto se puede hacer con un script sh que se utiliza en el campo 'script' de package.json y se ejecuta para iniciar.

Express 3 cambió esto porque:

La configuración "ver opciones" ya no es necesaria, aplicación.los locales son las variables locales fusionadas con las de res. render (), así que [app.local.pretty = true es lo mismo que pasar res.render(view, { pretty: true }).

 305
Author: EhevuTov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-24 22:48:30

A la salida html" pretty-format " en Jade / Express:

app.set('view options', { pretty: true });
 50
Author: Jonathan Julian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-29 01:05:48

Hay una opción" bonita " en Jade mismo:

var jade = require("jade");

var jade_string = [
    "!!! 5",
    "html",
    "    body",
    "        #foo  I am a foo div!"
].join("\n");

var fn = jade.compile(jade_string, { pretty: true });
console.log( fn() );

...te da esto:

<!DOCTYPE html>
<html>
  <body>
    <div id="foo">I am a foo div!
    </div>
  </body>
</html>

No parece ser muy sofisticado, pero para lo que busco the el capacidad para depurar realmente el HTML que producen mis vistas's está bien.

 7
Author: Kevin Frost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-06 01:20:46

En express 4.x, agrega esto a tu aplicación.js:

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}
 6
Author: alarive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-20 22:24:26

Si estás usando la consola para compilar, entonces puedes usar algo como esto:

$ jade views/ --out html --pretty
 4
Author: Tom Sarduy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-26 16:50:38

¿Realmente necesita html con un buen formato? Incluso si intentas generar algo que se vea bien en un editor, puede parecer raro en otro. Concedido, No se lo que necesita el html para, pero yo intentaría usar las herramientas de desarrollo de Chrome o firebug para Firefox. Esas herramientas le dan una buena vista del DOM en lugar del html.

Si realmente necesita html con un formato agradable, intente usar EJS en lugar de jade. Eso significaría que tendrías que formatear el html tú mismo.

 0
Author: Oscar Kilhed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-14 11:13:39

Puedes usar tidy

Tomemos por ejemplo este archivo jade:

Foo.jade

h1 MyTitle

p
  a(class='button', href='/users/') show users

table
  thead
    tr
      th Name
      th Email
  tbody
    - var items = [{name:'Foo',email:'foo@bar'}, {name:'Bar',email:'bar@bar'}]
    - each item in items
      tr
        td= item.name
        td= item.email

Ahora puede procesarlo con node testjade.js foo.jade > salida.html :

Testjade.js

var jade = require('jade');
var jadeFile = process.argv[2];
jade.renderFile(__dirname + '/' + jadeFile, options, function(err, html){
    console.log(html);
});

Te dará s.th. like:

Salida.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><title>My Title</title><link rel="stylesheet" href="/stylesheets/style.css"/><script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script></head><body><div id="main"><div ><h1>MyTitle</h1><p><a href="/users/" class="button">show users</a></p><table><thead><tr><th>Name</th><th>Email</th></tr></thead><tbody><tr><td>Foo</td><td>foo@bar</td></tr><tr><td>Bar</td><td>bar@bar</td></tr></tbody></table></div></div></body></html

Luego ejecutándolo a través de tidy con la salida tidy-m.html dará como resultado:

Salida.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux (vers 25 March 2009), see www.w3.org" />
<title>My Title</title>
<link rel="stylesheet" href="/stylesheets/style.css" type=
"text/css" />
<script type="text/javascript" src="../js/jquery-1.4.4.min.js">
</script>
</head>
<body>
<div id="main">
<div>
<h1>MyTitle</h1>
<p><a href="/users/" class="button">show users</a></p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td>foo@bar</td>
</tr>
<tr>
<td>Bar</td>
<td>bar@bar</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
 0
Author: oliver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-27 09:26:15

Basándose en la sugerencia de Oliver, aquí hay una manera rápida y sucia de ver html embellecido

1) descargar ordenar

2) añadir esto a su .bashrc

function tidyme() {
curl $1 | tidy -indent -quiet -output tidy.html ; open -a 'google chrome' tidy.html
}

3) ejecutar

$ tidyme localhost:3000/path

El comando open solo funciona en mac. espero que ayude!

 0
Author: ebaum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-11 20:41:48

En express 4.x, agrega esto a tu aplicación.js:

app.locals.pretty = app.get('env') === 'development';
 0
Author: petkovic43,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-13 14:11:01