build: ability to add html files as frappe.templates[filename] and related fixes to query report

This commit is contained in:
Rushabh Mehta 2014-06-13 10:41:48 +05:30
parent f0b8922e28
commit 2a3684a02c
9 changed files with 66 additions and 59 deletions

View file

@ -1,5 +1,5 @@
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
@ -16,7 +16,7 @@ def bundle(no_compress, make_copy=False):
# build js files
make_asset_dirs(make_copy=make_copy)
build(no_compress)
def watch(no_compress):
"""watch and rebuild if necessary"""
import time
@ -25,18 +25,18 @@ def watch(no_compress):
while True:
if files_dirty():
build(no_compress=True)
time.sleep(3)
def make_asset_dirs(make_copy=False):
assets_path = os.path.join(frappe.local.sites_path, "assets")
for dir_path in [
os.path.join(assets_path, 'js'),
os.path.join(assets_path, 'js'),
os.path.join(assets_path, 'css')]:
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# symlink app/public > assets/app
for app_name in frappe.get_all_apps(True):
pymodule = frappe.get_module(app_name)
@ -53,7 +53,7 @@ def build(no_compress=False):
assets_path = os.path.join(frappe.local.sites_path, "assets")
for target, sources in get_build_maps().iteritems():
pack(os.path.join(assets_path, target), sources, no_compress)
pack(os.path.join(assets_path, target), sources, no_compress)
shutil.copy(os.path.join(os.path.dirname(os.path.abspath(frappe.__file__)), 'data', 'languages.txt'), frappe.local.sites_path)
# reset_app_html()
@ -79,39 +79,46 @@ def get_build_maps():
else:
s = os.path.join(app_path, source)
source_paths.append(s)
build_maps[target] = source_paths
except Exception, e:
print path
raise
return build_maps
timestamps = {}
def pack(target, sources, no_compress):
from cStringIO import StringIO
outtype, outtxt = target.split(".")[-1], ''
jsm = JavascriptMinify()
for f in sources:
suffix = None
if ':' in f: f, suffix = f.split(':')
if not os.path.exists(f) or os.path.isdir(f): continue
timestamps[f] = os.path.getmtime(f)
try:
with open(f, 'r') as sourcefile:
with open(f, 'r') as sourcefile:
data = unicode(sourcefile.read(), 'utf-8', errors='ignore')
if outtype=="js" and (not no_compress) and suffix!="concat" and (".min." not in f):
extn = f.rsplit(".", 1)[1]
if outtype=="js" and extn=="js" and (not no_compress) and suffix!="concat" and (".min." not in f):
tmpin, tmpout = StringIO(data.encode('utf-8')), StringIO()
jsm.minify(tmpin, tmpout)
outtxt += unicode(tmpout.getvalue() or '', 'utf-8').strip('\n') + ';'
elif outtype=="js" and extn=="html":
# add to frappe.templates
content = data.replace("\n", " ").replace("'", "\'")
outtxt += """frappe.templates["{key}"] = '{content}';\n""".format(\
key=f.rsplit("/", 1)[1][:-5], content=content)
else:
outtxt += ('\n/*\n *\t%s\n */' % f)
outtxt += '\n' + data + '\n'
except Exception, e:
print "--Error in:" + f + "--"
print frappe.get_traceback()
@ -119,10 +126,10 @@ def pack(target, sources, no_compress):
if not no_compress and outtype == 'css':
pass
#outtxt = cssmin(outtxt)
with open(target, 'w') as f:
f.write(outtxt.encode("utf-8"))
print "Wrote %s - %sk" % (target, str(int(os.path.getsize(target)/1024)))
def files_dirty():
@ -135,4 +142,4 @@ def files_dirty():
return True
else:
return False

View file

@ -50,7 +50,6 @@
"public/js/lib/center_image.js",
"public/js/lib/bootstrap.min.js",
"public/js/lib/nprogress.js",
"public/js/lib/microtemplate.js",
"public/js/lib/beautify-html.js",
"public/js/lib/moment/moment.min.js",
"public/js/lib/moment/moment-timezone.min.js",
@ -67,6 +66,9 @@
"public/js/frappe/router.js",
"public/js/frappe/desk.js",
"public/js/frappe/defaults.js",
"public/js/lib/microtemplate.js",
"public/html/print_template.html",
"public/js/legacy/globals.js",
"public/js/legacy/datatype.js",

View file

@ -6,12 +6,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>{0}</title>
<link href="/assets/frappe/css/bootstrap.css" rel="stylesheet">
<title>{%= title %}</title>
<link href="{%= frappe.urllib.get_base_url() %}/assets/frappe/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
{1}
{%= content %}
</div>
</body>
</html>

View file

@ -248,13 +248,4 @@ frappe.utils = {
setTimeout(function() { callback(dataURL); }, 10 );
}
},
with_print_template: function(fn) {
if(!frappe.print_template) {
$.get("/assets/frappe/html/print_template.html?q=4",
function(html) { frappe.print_template = html; fn(); });
} else {
fn();
}
}
};

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
// MIT License. See license.txt
// provide a namespace
if(!window.frappe)
if(!window.frappe)
window.frappe = {};
frappe.provide = function(namespace) {
// docs: create a namespace //
@ -22,4 +22,5 @@ frappe.provide("locals");
frappe.provide("frappe.settings");
frappe.provide("frappe.utils");
frappe.provide("frappe.ui");
frappe.provide("frappe.modules");
frappe.provide("frappe.modules");
frappe.provide("frappe.templates");

View file

@ -133,21 +133,25 @@ frappe.views.QueryReport = Class.extend({
msgprint(__("Run the report first"));
return;
}
frappe.utils.with_print_template(function() {
var data = [];
$.each(me.data, function(i, d) {
var newd = {}; data.push(newd);
$.each(d, function(k, v) {
newd[k.replace(/ /g, "_").toLowerCase()] = v; });
});
var content = tmpl.render(html_format, {data: data, filters:me.get_values(), report:me});
var html = $.format(frappe.print_template, [
__(me.report_name), content]);
var w = window.open();
w.document.write(html);
w.document.close();
})
var data = [];
$.each(me.data, function(i, d) {
var newd = {}; data.push(newd);
$.each(d, function(k, v) {
newd[k.replace(/ /g, "_").toLowerCase()] = v; });
});
var content = frappe.render(html_format,
{data: data, filters:me.get_values(), report:me});
var html = frappe.render(frappe.templates.print_template, {
title: __(me.report_name), content: content
});
var w = window.open();
w.document.write(html);
w.document.close();
}, "icon-print");
}

View file

@ -1,12 +1,13 @@
// Simple JavaScript Templating
// Adapted from John Resig - http://ejohn.org/ - MIT Licensed
tmpl = {compiled: {}, debug:{}};
tmpl.compile = function(str) {
frappe.template = {compiled: {}, debug:{}};
frappe.template.compile = function(str) {
if(str.indexOf("'")!==-1) {
console.log("Warning: Single quotes (') may not work in templates");
}
if(!tmpl.compiled[str]) {
fn_str = "var p=[],print=function(){try{p.push.apply(p,arguments)}catch(e){console.log([p, e]);};};" +
if(!frappe.template.compiled[str]) {
fn_str = "var p=[],print=function(){p.push.apply(p,arguments)};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
@ -22,12 +23,12 @@ tmpl.compile = function(str) {
.split("\r").join("\\'")
+ "');}return p.join('');";
tmpl.debug[str] = fn_str;
tmpl.compiled[str] = new Function("obj", fn_str);
frappe.template.debug[str] = fn_str;
frappe.template.compiled[str] = new Function("obj", fn_str);
}
return tmpl.compiled[str];
return frappe.template.compiled[str];
};
tmpl.render = function(str, data, debug) {
return tmpl.compile(str)(data);
frappe.render = function(str, data, debug) {
return frappe.template.compile(str)(data);
};

View file

@ -124,5 +124,6 @@ frappe.ready(function() {
window.location.hash = "#login";
login.bind_events();
login.login();
$(".form-signup, .form-forgot").removeClass("hide");
$(document).trigger('login_rendered');
});

View file

@ -43,7 +43,7 @@
</form>
<form class="form-signin form-signup" role="form">
<form class="form-signin form-signup hide" role="form">
<h2 class="form-signin-heading">{{ _("Sign Up") }}</h2>
<input type="text" id="signup_fullname"
class="form-control" placeholder="{{ _('Full Name') }}" required autofocus>
@ -56,7 +56,7 @@
</form>
<form class="form-signin form-forgot" role="form">
<form class="form-signin form-forgot hide" role="form">
<h2 class="form-signin-heading">{{ _("Forgot Password") }}</h2>
<input type="email" id="forgot_email"
class="form-control" placeholder="{{ _('Email Id') }}" required autofocus>