def extract(fileobj, keywords, comment_tags, options): """Extract messages from SUIT template files using Babel. Original extraction code thanks to `Brandon Evans <http://brandonevans.org/>`_. ``fileobj`` The file-like object the messages should be extracted from. ``keywords`` a list of keywords (i.e. function names) that should be recognized as translation functions. ``comment_tags`` a list of translator tags to search for and include in the results ``options`` a dictionary of additional options (optional) """ global messages rules = { '[gettext]': { 'close': '[/gettext]', 'functions': [walk, gettext] } } suit.execute(rules, fileobj.read()) for message in messages: yield ('', '[gettext]', message, '')
def gravatar(params): """Return a Gravatar for the given email address. **Syntax:** [gravatar]email[/gravatar] **Attributes** ``markup`` What the markup for the given Gravatar should be once generated. The URL for the Gravatar is available as [c]_gravatar[/c]. (**Optional**. Default: `<img src="[c]_gravatar[/c]" alt="">`) ``rating`` The rating for the given Gravatar. (**Optional**. Default: PG) ``size`` The size for the given Gravatar. (**Optional**. Default: 80) ``default`` The default image to use if the given email address does not have a Gravatar. (**Optional**. Default: identicon) """ email_hash = hashlib.md5(params['string']).hexdigest() rating = params['var']['rating'] size = params['var']['size'] default = params['var']['default'] format = 'http://www.gravatar.com/avatar/%s?r=%s&s=%s&d=%s' c._gravatar = format % (email_hash, rating, size, default) params['string'] = suit.execute(suitlons.rules, params['var']['markup']) return params
def template(params): """Substitute variables into the template.""" templating.var.equal = params['var']['equal'] templating.var.string = params['string'] params['string'] = suit.execute(templating.rules, params['var']['template']) return params
def render(template, rules=None, slacks=False): """Load and execute a template file from the template directory based on the rules provided, and optionally enable SLACKS debugging. ``template`` Filename, relative to the project's template directory. For example, >> template = render('template.tpl') >> template = render('directory/template.tpl') ``rules`` A dict containing SUIT rules. (**Optional**. Default: config['suit.rules']) ``slacks`` Whether or not a SLACKS log is available for download for debugging purposes.(**Optional**. Default: False) Once this argument is passed, to view a SLACKS log is a simple matter of appending the `slacks` querystring to the URL. For example, assume we have a page whose URL is mapped to /index and has SLACKS enabled. The URL to request the SLACKS log would be, ``/index?slacks=true``. It is also important to note that this argument should only be passed once, and only to the "entry point template," which is to say, in cases such as: >>> class SomeController(BaseController): >>> def index(self): >>> return render('index.tpl', slacks=True) """ filepath = os.path.join( config['pylons.paths']['templates'], os.path.normpath(template) ) if not rules: rules = config['suit.rules'] try: content = open(filepath).read() except IOError: raise IOError('Template does not exist: %s' % filepath) result = suit.execute(rules, content) defaultlog = {'hash': {}, 'contents': []} if 'slacks' in request.params and slacks: # Granted slacks is enabled for this template and receive a request # for slacks, then return JSON'd output instead. slacks = json.dumps(suit.log, separators=(',',':')) suit.log = defaultlog response.headerlist = [ ('Pragma', 'public'), ('Expires', '0'), ('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'), ('Content-type', 'text/json'), ('Content-Disposition', 'attachment; filename=slacks.json'), ('Content-Length', len(slacks)) ] return slacks return result
def template(params): """Substitute variables into the template.""" templating.var.equal = params['var']['equal'] templating.var.string = params['string'] params['string'] = suit.execute( templating.rules, params['var']['template'] ) return params
def execute(params): """Execute the string using the same rules used in this template.""" config = params['config'].copy() config['log'] = params['var']['log'] params['string'] = suit.execute( params['rules'], params['string'], config ) return params
def attribute(params): """Create rule out of attributes.""" variable = params['rules'][params['tree']['rule']]['var'].copy() params['var'] = variable['var'].copy() # Decide where to get the attributes from. if 'onesided' in variable and variable['onesided']: string = params['string'] elif 'create' in params['tree']: string = params['tree']['create'] else: return params quote = '' smallest = False # Decide which quote string to use based on which occurs first. for value in variable['quote']: haystack = string needle = value if params['config']['insensitive']: haystack = haystack.lower() needle = needle.lower() position = haystack.find(needle) if position != -1 and (smallest == False or position < smallest): quote = value smallest = position if quote: # Split up the string by quotes. split = string.split(quote) del split[-1] for key, value in enumerate(split): # If this is the opening quote. if key % 2 == 0: name = value.strip() syntax = ( name[ len(name) - len(variable['equal']) ] == variable['equal'] ) name = name[0:len(name) - len(variable['equal'])] # If the syntax is not valid or the variable is not whitelisted # or blacklisted, do not prepare to define the variable. if not syntax or not listing(name, variable): name = '' elif name: # Define the variable. config = params['config'].copy() config['log'] = variable['log'] params['var'][name] = suit.execute( params['rules'], value, config ) return params
def attribute(params): """Create rule out of attributes.""" variable = params['rules'][params['tree']['rule']]['var'].copy() params['var'] = variable['var'].copy() # Decide where to get the attributes from. if 'onesided' in variable and variable['onesided']: string = params['string'] elif 'create' in params['tree']: string = params['tree']['create'] else: return params quote = '' smallest = False # Decide which quote string to use based on which occurs first. for value in variable['quote']: haystack = string needle = value if params['config']['insensitive']: haystack = haystack.lower() needle = needle.lower() position = haystack.find(needle) if position != -1 and (smallest == False or position < smallest): quote = value smallest = position if quote: # Split up the string by quotes. split = string.split(quote) del split[-1] for key, value in enumerate(split): # If this is the opening quote. if key % 2 == 0: name = value.strip() syntax = (name[len(name) - len(variable['equal'])] == variable['equal']) name = name[0:len(name) - len(variable['equal'])] # If the syntax is not valid or the variable is not whitelisted # or blacklisted, do not prepare to define the variable. if not syntax or not listing(name, variable): name = '' elif name: # Define the variable. config = params['config'].copy() config['log'] = variable['log'] params['var'][name] = suit.execute(params['rules'], value, config) return params
def execute(params): """Execute the string using the same rules used in this template.""" config = params['config'].copy() config['log'] = params['var']['log'] params['string'] = suit.execute(params['rules'], params['string'], config) return params