Skip to content

Instantly share code, notes, and snippets.

@mkoryak
Created December 4, 2014 19:30
Show Gist options
  • Save mkoryak/10c0868cf3fe609d8413 to your computer and use it in GitHub Desktop.
Save mkoryak/10c0868cf3fe609d8413 to your computer and use it in GitHub Desktop.
use flask's url_for in javascript
{% autoescape false %}
(function(){
var ruleMap = {{ rule_map }};
X = X || {};
X.url_for = function(endpoint, params) {
var re = /\<\s*(\w+:)*(\w+)\s*\>/ig;
if (!params) {
params = {};
}
if (!ruleMap[endpoint]) {
throw('endpoint is not exist: ' + endpoint);
}
var anchor = null;
var base = "";
if(params['_external']){
base = "{{ web_host }}";
delete params['_external'];
}
if(params['_anchor']){
anchor = "#"+params['_anchor'];
delete params['_anchor'];
}
var rules = ruleMap[endpoint];
var url = null;
var errors = [];
$.each(rules, function(){
var rule = this;
var used_params = {};
var unbuildable = false;
var path = rule.replace(re, function (_i, _0, _1) {
if (params.hasOwnProperty(_1)) {
used_params[_1] = params[_1];
return encodeURIComponent(params[_1]);
} else {
errors.push(_1 + ' does not exist in params for: '+rule);
unbuildable = true;
}
});
if(unbuildable || url) {
return;
}
var query_string = '';
for (var k in params) {
if (used_params.hasOwnProperty(k)) {
continue;
}
var v = params[k];
if (query_string.length > 0) {
query_string += '&';
}
query_string += encodeURIComponent(k) + '=' + encodeURIComponent(v);
}
url = path;
if (query_string.length > 0) {
url += '?' + query_string;
}
});
if(!url){
throw(errors.join(", "))
}
if(anchor){
url = url+anchor;
}
return base+url;
}
X.url_for.rules = ruleMap;
})();
{% endautoescape %}
@route("/routes.js", methods=["GET"])
def js_routes(self):
from flask import current_app, render_template
import simplejson as json
rule_map = defaultdict(list)
for rule in current_app.url_map.iter_rules():
rule_map[rule.endpoint].append(rule.rule)
content = render_template("js_routes.html", {'rule_map':json.dumps(rule_map), 'web_host':config.get('WEB_HOST'))})
return Response(
content,
content_type='text/javascript; charset=UTF-8',
headers={
'Cache-Control': 'no-cache',
}
)
X.url_for('app.my_awesome_route', {id: 5, _external=True}) //make external url
/*
This requires jquery, but can easily not, since it just uses $.each in there
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment