1 | # Stringify #
|
2 |
|
3 | Browserify plugin to require() text files (like templates) inside of your client-side JavaScript files.
|
4 |
|
5 | ## Installation ##
|
6 |
|
7 | ```bash
|
8 | npm install stringify
|
9 | ```
|
10 |
|
11 | ## Usage ##
|
12 |
|
13 | Setup Browserify to use this middleware in your app:
|
14 |
|
15 | ```javascript
|
16 | var browserify = require('browserify'),
|
17 | stringify = require('stringify');
|
18 |
|
19 | var bundle = browserify()
|
20 | .use(stringify(['.hjs', '.html', '.whatever']))
|
21 | .addEntry('my_app_main.js');
|
22 |
|
23 | app.use(bundle);
|
24 | ```
|
25 | You might have noticed that you can pass stringify an optional array of file-extensions that you want to require() in your Browserify packages as strings. By default these are used: .html, .txt, .text, and .tmpl
|
26 |
|
27 | __NOTE__: You MUST call this as I have above. The Browserify .use() method HAS to plug this middleware in to Browserify BEFORE you add the entry point (your main client-side file) for Browserify.
|
28 |
|
29 | Now, in your clientside files you can use require() as you would for JSON and JavaScript files, but include text files that have just been parsed into a JavaScript string:
|
30 |
|
31 | ```javascript
|
32 | var my_text = require('../path/to/my/text/file.txt');
|
33 |
|
34 | console.log(my_text);
|
35 | ```
|
36 |
|
37 | ## More Realistic Example & Use-Case ##
|
38 |
|
39 | The reason I created this was to get string versions of my Handlebars templates required in to my client-side JavaScript. You can theoretically use this for any templating parser though.
|
40 |
|
41 | Here is how that is done:
|
42 |
|
43 | application.js:
|
44 | ```javascript
|
45 | var browserify = require('browserify'),
|
46 | stringify = require('stringify');
|
47 |
|
48 | var bundle = browserify()
|
49 | .use(stringify(['.hbs', '.handlebars']))
|
50 | .addEntry('my_app_main.js');
|
51 |
|
52 | app.use(bundle);
|
53 | ```
|
54 |
|
55 | my_app_main.js:
|
56 | ```javascript
|
57 | var Handlebars = require('handlebars'),
|
58 | template = require('my/template/path.hbs'),
|
59 | data = require('data.json');
|
60 |
|
61 | var hbs_template = Handlebars.compile(template);
|
62 |
|
63 | // Now I can use hbs_template like I would anywhere else, passing it data and getting constructed HTML back.
|
64 | var constructed_template = hbs_template(data);
|
65 |
|
66 | /*
|
67 | Now 'constructed_template' is ready to be appended to the DOM in the page!
|
68 | The result of it should be:
|
69 |
|
70 | <p>This is my string!</p>
|
71 | */
|
72 | ```
|
73 |
|
74 | my/template/path.hbs:
|
75 | ```html
|
76 | <p>{{ json_data }}</p>
|
77 | ```
|
78 |
|
79 | data.json
|
80 | ```json
|
81 | {
|
82 | "json_data": "This is my string!"
|
83 | }
|
84 | ```
|