A
A
Alexey Sosnovsky2015-07-09 10:20:15
JavaScript
Alexey Sosnovsky, 2015-07-09 10:20:15

How to build a jade template on the client side (in the browser) using javascript on the fly?

build project with gulp

var gulp = require("gulp");
var connect = require("gulp-connect");
var opn = require("opn");
var jade = require('gulp-jade');

//запускаем локальный сервер
gulp.task('connect', function() {
    connect.server({
        root: 'app',
        livereload: true,
        port: 8888
    });
    opn('http://localhost:8888');
});

//работа с HTML
gulp.task('html', function () {
    gulp.src('./app/*.html')
        .pipe(connect.reload());
});

//работа с CSS
gulp.task('css', function () {
    gulp.src('./app/css/*.css')
        .pipe(connect.reload());
});

//работа с JS
gulp.task('js', function () {
    gulp.src('./app/js/*.js')
        .pipe(connect.reload());
});

// работа с шаблонами JADE
gulp.task('jade', function() {
    var YOUR_LOCALS = {};

    gulp.src('./app/jade/index.jade')
        .pipe(jade({
            locals: YOUR_LOCALS,
            // красивый (не ужатый) вывод
            pretty: true
        }))
        .pipe(gulp.dest('./app/'))
});

//WATCHER
gulp.task('watch', function () {
    gulp.watch(['./app/*.html'], ['html']);
    gulp.watch(['./app/css/*.css'], ['css']);
    gulp.watch(['./app/js/*.js'], ['js']);
    gulp.watch(['./app/jade/*.jade'], ['jade']);
});

//DEFAULT
gulp.task('default', ['connect', 'watch']);

there is a jade template
doctype html
html
    head
        title autokeys
        meta(charset="utf-8")
        link(href="bower/normalize.css/normalize.css", rel="stylesheet")
        link(href="css/main.css", rel="stylesheet")
    body

        //фильтр автоключей
        .top
            select#vendor.car-select
                option(disabled) Выберите марку
            select#model.car-select
                option(disabled) Выберите модель
            select#year.car-select
                option(disabled) Выберите год
        #result

and there is JS that processes events on select and generates product cards
var vendor = document.getElementById("vendor");
var model = document.getElementById("model");
var year = document.getElementById("year");
var result = document.getElementById("result");
var selectedVendor;
var selectedModel;
var selectedYear;

$(function(){
    $.getJSON('data.json', function(data) {
        $.each(data.cars, function(key, val) {
            $('#vendor').append('<option value="' + val + '">' + key + '</option>');
        });
    });
});


vendor.onchange = function(){
    selectedVendor = vendor.options[vendor.selectedIndex].text;
    model.innerHTML='Выберите модель';
    year.innerHTML='Выберите модель';
    $('#year').append('<option disabled selected>Выберите год выпуска</option>');

    $(function(){
        $.getJSON('data.json', function(data) {
            $('#model').append('<option disabled selected>Выберите модель</option>');
            $.each(data.cars[selectedVendor], function(key, val) {
                $('#model').append('<option value="' + val + '">' + key + '</option>');
            });
        });


    });
};


model.onchange = function(){
    selectedModel = model.options[model.selectedIndex].text;
    year.innerHTML='Выберите год';

    $(function(){
        $.getJSON('data.json', function(data) {
            $('#year').append('<option disabled selected>Выберите год выпуска</option>');
            $.each(data.cars[selectedVendor][selectedModel], function(key, val) {
                $('#year').append('<option value="' + val + '">' + key + '</option>');
            });
        });


    });
};

year.onchange = function(){
    selectedYear = year.options[year.selectedIndex].text;
    result.innerHTML='';
    $(function(){
        $.getJSON('data.json', function(data) {


            $.each(data.cars[selectedVendor][selectedModel][selectedYear], function(key, val)  {

                $('#result').append(
                    '<div class="key-item">'+
                    '<img class="key-image" src="img/' + val.pic + '.jpg" alt="key image">' +
                    '<div>' + key + '</div>' +
                    '<div>' + 'цена: ' +  val.price + '</div>'+
                    '</div>'


                );
            });
        });
    });
};

I would like to get rid of the ugliness
$('#result').append(
                    '<div class="key-item">'+
                    '<img class="key-image" src="img/' + val.pic + '.jpg" alt="key image">' +
                    '<div>' + key + '</div>' +
                    '<div>' + 'цена: ' +  val.price + '</div>'+
                    '</div>'


                );

and I made in a separate file a small template for separately generating a product card
table.good-item
   tr
      td(rowspan=7)
         img(src="./img/toyota-3.jpg", width="100", height="100", alt="ключ")
   tr
      td(colspan=4) goodname #{title} blah-blah-blah uuurrrr-la-la
   tr
      td(colspan=4) good notice wmfew sdfopgwerpfgvm vjk mfo[eibjr odkfv pdfk e[g kndfgkj nefgdb
   tr
      td стоимость чипа
      td !!!стоимость!!!чипа
      td в наличии
      td есть
   tr
      td программирование ключа
      td 4
      td самовывоз
      td 1 день
   tr
      td заточка лезвия
      td 4
      td курьером
      td 2 дня
   tr
      td итого
      td 4
      td(colspan=2)
         button ЗАКАЗАТЬ

and I would like to generate in this cycle when choosing in select
$.each(data.cars[selectedVendor][selectedModel][selectedYear], function(key, val)

this template with filled in data for each key.
I can’t understand how to do this at all :(
help someone who understands JADE

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-07-09
Protko @Fesor

will not work on the client. Well, of course there are solutions , but they have not been supported for a long time and it is stuck on the old version of jade.
Instead, I propose to implement a simple template manager that provides a simple interface:

templateManager.get('tpl/something.html');
templateManager.put('tpl/something.html, 'some template');

for development, this thing can load assembled templates via ajax, and for production it would be possible to compile a simple file from all this that would shove it all there. By analogy with the angular template cache is shorter.
updated
even blunted by me, gulp-jade has a client option , then jade will compile to js that you can already use.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question