Skip to content

Commit

Permalink
Merge pull request #256 from 2gis/fix/templates-build
Browse files Browse the repository at this point in the history
Research template engines
  • Loading branch information
andymost committed Jun 26, 2015
2 parents 058e188 + dbfa339 commit 2f930c4
Show file tree
Hide file tree
Showing 13 changed files with 81 additions and 65 deletions.
2 changes: 1 addition & 1 deletion gulp/deps/deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ var deps = {
all: ['DGRuler/skin/{skin}/less/dg-ruler.less'],
ie: ['DGRuler/skin/{skin}/less/dg-ruler.ie.less']
},
deps: ['DGCore', 'DGLocale', 'DGDust']
deps: ['DGCore', 'DGLocale']
},

DGRulerControl: {
Expand Down
11 changes: 8 additions & 3 deletions gulp/tasks/buildScripts.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
var sourcemaps = require('gulp-sourcemaps');
var streamqueue = require('streamqueue');
var uglify = require('gulp-uglify');
var header = require('gulp-header');
var redust = require('gulp-redust');
var concat = require('gulp-concat');
var footer = require('gulp-footer');
var es = require('event-stream');
var dust = require('gulp-dust');
var gulpif = require('gulp-if');
var util = require('gulp-util');
var map = require('map-stream');
var gulp = require('gulp');

var config = require('../../app/config.js');
var deps = require('../deps')(config);

var templateStream = require('../util/templateStream');
var projectList = require('../util/projectList');
var error = require('../util/error');
var stat = require('../util/stat');
Expand All @@ -29,10 +32,12 @@ gulp.task('buildScripts', dependencies, function () {
}

return packages.map(function (pkg) {
return gulp.src(deps.getJSFiles({pkg: pkg}), {base: '.'})
return streamqueue({objectMode: true},
gulp.src(deps.getJSFiles({pkg: pkg}), {base: '.'}),
templateStream(pkg)
)
.pipe(error.handle())
.pipe(gulpif(!util.env.release, sourcemaps.init()))
.pipe(redust(config.tmpl))
.pipe(concat('script.' + (!isCustom ? pkg + '.' : '') + 'js'))
.pipe(header(config.js.intro))
.pipe(footer(projectList.get()))
Expand Down
11 changes: 7 additions & 4 deletions gulp/tasks/buildTestScripts.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var redust = require('gulp-redust');
var streamqueue = require('streamqueue');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var header = require('gulp-header');
Expand All @@ -9,6 +9,7 @@ var gulpif = require('gulp-if');
var util = require('gulp-util');
var gulp = require('gulp');

var templateStream = require('../util/templateStream');
var config = require('../../app/config.js');
var deps = require('../deps')(config);
var projectList = require('../util/projectList');
Expand All @@ -22,9 +23,11 @@ gulp.task('buildTestScripts', ['loadProjectList', 'lintJS', 'buildLeaflet'], fun
// no loading tiles
config.appConfig.tileServer = '';

var stream = gulp.src(deps.getJSFiles({pkg: pkg}), {base: '.'})
.pipe(error.handle())
.pipe(redust(config.tmpl));
var stream = streamqueue({objectMode: true},
gulp.src(deps.getJSFiles({pkg: pkg}), {base: '.'}),
templateStream(pkg).pipe(concat('templates.js'))
)
.pipe(error.handle());

if (isConcat) {
stream = stream
Expand Down
1 change: 1 addition & 0 deletions gulp/tasks/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ gulp.task('test', testRequirements, function () {
var sourcesList = deps.getJSFiles({source: 'testSource'}).concat([
'gulp/tmp/testJS/config.js',
'gulp/tmp/testJS/projectList.js',
'gulp/tmp/testJS/templates.js',
'node_modules/leaflet/spec/after.js',
'node_modules/happen/happen.js',
'node_modules/mock-geolocation/dist/geolocate.js'
Expand Down
22 changes: 22 additions & 0 deletions gulp/util/templateStream.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
var path = require('path');
var gulp = require('gulp');
var dust = require('gulp-dust');

var config = require('../../app/config.js');
var deps = require('../deps')(config);

module.exports = function (pkg) {
var templateList = deps.getModulesList(pkg)
.map(function(moduleName) {
return 'src/' + moduleName + '/templates/*.dust';
});

return gulp.src(templateList).pipe(dust({
name: function (file) {
var moduleName = path.basename(path.dirname(path.dirname(file.path)));
var templateName = path.basename(file.relative, '.dust');

return moduleName + '/' + templateName;
}
}));
}
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"gulp-bump": "0.1.13",
"gulp-cached": "^1.1.0",
"gulp-concat": "^2.2.0",
"gulp-dust": "^2.0.0",
"gulp-eslint": "^0.7.0",
"gulp-file": "0.2.0",
"gulp-flatten": "0.0.4",
Expand All @@ -42,7 +43,6 @@
"gulp-minify-css": "^0.5.1",
"gulp-notify": "^2.2.0",
"gulp-plumber": "0.6.6",
"gulp-redust": "0.0.1",
"gulp-remember": "^0.3.0",
"gulp-rename": "^1.2.0",
"gulp-replace": "^0.5.3",
Expand All @@ -54,8 +54,8 @@
"happen": "0.1.3",
"html5shiv": "^3.7.2",
"image-size": "0.3.5",
"less": "^2.4.0",
"leaflet": "git://github.com/Leaflet/Leaflet.git#1bb1b5a3f8307b4460211f340281b764a24a13cc",
"less": "^2.4.0",
"lodash": "^2.4.1",
"map-stream": "0.1.0",
"marked": "0.3.3",
Expand All @@ -65,7 +65,8 @@
"pretty-bytes": "^1.0.2",
"request": "^2.53.0",
"require-dir": "^0.1.0",
"run-sequence": "^1.0.2"
"run-sequence": "^1.0.2",
"streamqueue": "^1.1.0"
},
"devDependencies": {
"coveralls": "^2.11.2",
Expand Down
4 changes: 1 addition & 3 deletions src/DGAttribution/src/DGAttribution.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,6 @@ DG.Control.Attribution.include({

this._container.innerHTML = copyright + prefixAndAttribs.join(' | ');
},
/* global __DGAttribution_TMPL__ */
_tmpl: DG.dust(__DGAttribution_TMPL__),
_getData: function (lang) {
return {
'osm': this._osm,
Expand All @@ -121,7 +119,7 @@ DG.Control.Attribution.include({
};
},
_getAttributionHTML: function (lang) {
return this._tmpl('copyright', this._getData(lang));
return DG.dust('DGAttribution/copyright', this._getData(lang));
},
_renderTranslation: function (e) {
this._update(e.lang);
Expand Down
20 changes: 8 additions & 12 deletions src/DGDust/doc/DGDust.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## DG.dust

Используется для шаблонизации в Javascript. Использует шаблонизатор [dustjs(fork Linkedin)](http://linkedin.github.io/dustjs/)
Используется для шаблонизации в Javascript. Использует шаблонизатор [dustjs (fork Linkedin)](http://linkedin.github.io/dustjs/)

### Функция-конструктор

Expand All @@ -12,12 +12,12 @@
</tr>
<tr>
<td>
<code>DG.dust(<b>Object</b><i> module templates</i>)</code>
<code><b>String</b><i> name of dust template</i>, <b>Object</b><i> data</i></code>
</td>
<td>
<code>function(<b>String</b><i> name of dust template</i>, <b>Object</b><i> data</i>)</code>
<code><b>String</b><i> rendered template</i></code>
</td>
<td>Считывает скомпилированые шаблоны модуля и возвращает функцию, которая используеться как рендер шаблонов. Она принимает имя шаблона и данные для подстановки и возвращает строку с итоговым html кодом.</td>
<td>Функция, выполняющая рендер шаблона. Принимает имя шаблона и данные для подстановки и возвращает строку с итоговым html-кодом. Имя шаблона имеет следующий вид: имя_модуля/имя_файла_с_шаблоном; например: DGAttribution/copyright</td>
</tr>
</table>

Expand All @@ -29,13 +29,9 @@
* **DGTraffic/**
* **...**
* **templates/**
* baloon.dust
* balloon.dust
* firmCard.dust

Чтобы получить доступ к шаблонам модуля нужно объявить переменную `__ModuleName_TMPL__` (например `__DGTraffic_TMPL__`). Эта переменная при сборке будет заменена на объект со всеми шаблонами модуля и их содержимым (обращение по имени файла шаблона, то есть: содержимое шаблона baloon.dust будет доступно через templates.balloon, а содержимое шаблона firmCard.dust через templates.firmCard):

```bash
var templates = DG.dust(__DGTraffic_TMPL__); // объект templates содержит все шаблоны модуля DGTraffic
templates(baloon) // вернет контент шаблона baloon.dust
templates(baloon, {title: 'hello'}) // вернет контент шаблона baloon.dust с подставленым title'ом
```
```js
var html = DG.dust('DGTraffic/balloon', {title: 'hello'}) // вернет контент шаблона balloon.dust с подставленым title'ом
```
19 changes: 7 additions & 12 deletions src/DGDust/src/DGDust.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
DG.dust = function (tmpl) {
return function (name, data) {
if (!dust.cache[name]) {
dust.loadSource(tmpl[name]);
}
DG.dust = function (name, data) {
var result;

var result;
// The callback is called synchronously, so this works
dust.render(name, data, function (err, html) {
result = html;
});

dust.render(name, data, function (err, html) {
result = html;
});

return result;
};
return result;
};

if (DG.debug) { dust.debugLevel = 'ERROR'; }
25 changes: 12 additions & 13 deletions src/DGGeoclicker/src/View.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,26 @@ DG.Geoclicker.View = DG.Class.extend({
closeOnClick: true
});

/*global __DGGeoclicker_TMPL__ */
this._templates = DG.dust(__DGGeoclicker_TMPL__);

if (options) {
DG.Util.setOptions(this, options);
}
},

initLoader: function (isSmall) {
var loader = document.createElement('div');
loader.innerHTML = this._templates('loader',
{
small: isSmall,
anim: this._detectCssAnimation()
}
);
loader.innerHTML = DG.dust('DGGeoclicker/loader', {
small: isSmall,
anim: this._detectCssAnimation()
});

return loader.firstChild;
},

showPopup: function (latlng, content) { // (Object)
this._popup
.setContent(content)
.setLatLng(latlng)
.openOn(this._map);
.setContent(content)
.setLatLng(latlng)
.openOn(this._map);
},

render: function (options) { // (Object) -> String
Expand All @@ -46,7 +41,7 @@ DG.Geoclicker.View = DG.Class.extend({
options.tmpl = options.tmpl || '';

if (options.data) {
html = this._templates(options.tmpl, options.data);
html = this.renderTemplate(options.tmpl, options.data);
} else {
html = options.tmpl;
}
Expand All @@ -72,6 +67,10 @@ DG.Geoclicker.View = DG.Class.extend({
return html;
},

renderTemplate: function (name, data) {
return DG.dust('DGGeoclicker/' + name, data);
},

renderPopup: function (options) { // (Object) -> String
options.popup = true;
return this.render(options);
Expand Down
2 changes: 1 addition & 1 deletion src/DGGeoclicker/src/handler/House.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ DG.Geoclicker.Handler.House = DG.Geoclicker.Handler.Default.extend({

_firmCardSetup: function () { //() -> Object
return {
render: this._view._templates,
render: this._view.renderTemplate,
lang: this._map.getLang(),
domain: this._controller.getMap().projectDetector.getProject().domain,
ajax: DG.bind(this._api.getFirmInfo, this._api),
Expand Down
15 changes: 9 additions & 6 deletions src/DGRuler/src/LayeredMarker.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
DG.Ruler.LayeredMarker = DG.Marker.extend({

/*global __DGRuler_TMPL__:false */

options: {
draggable: false,
keyboard: false,
riseOnHover: true,
iconHTML: DG.dust(__DGRuler_TMPL__)('RulerLayeredMarker', {
blankgif : 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
})
iconHTML: [
'<img class="dg-ruler__label-spacer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" width="26" height="26" />',
'<div class="dg-ruler__label-container">',
' <div class="dg-ruler__point"></div>',
' <span class="dg-ruler__label-distance">0 км</span>',
' <span class="dg-ruler__label-remove-link"></span>',
' <div class="dg-ruler__remove-link-overlay"></div>',
'</div>'
].join('\n')
},

statics: {
Expand Down
7 changes: 0 additions & 7 deletions src/DGRuler/templates/RulerLayeredMarker.dust

This file was deleted.

0 comments on commit 2f930c4

Please sign in to comment.