Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模板引擎,可以记录一些块的位置_Python_Templates_Python 2.7 - Fatal编程技术网

Python 模板引擎,可以记录一些块的位置

Python 模板引擎,可以记录一些块的位置,python,templates,python-2.7,Python,Templates,Python 2.7,我正在编写一个电子邮件客户端,我想实现一个类似于kmail模板中%CURSOR的东西:在显示生成的电子邮件消息后,标记光标应该放在的位置。什么模板引擎可以做这种事情?这与Python有什么关系?@Amber,因为我需要Python模板引擎。它与kmail没有直接关系:我正在编写邮件客户端,而不是kmail的插件。kmail在这里只是一个例子,我认为您不想在模板引擎中处理光标位置。相反,我会说,只要有一个标记,您稍后会检测到它,并将其从渲染模板中删除,以将光标放置在该标记上。@Amber如果找不到

我正在编写一个电子邮件客户端,我想实现一个类似于kmail模板中%CURSOR的东西:在显示生成的电子邮件消息后,标记光标应该放在的位置。什么模板引擎可以做这种事情?

这与Python有什么关系?@Amber,因为我需要Python模板引擎。它与kmail没有直接关系:我正在编写邮件客户端,而不是kmail的插件。kmail在这里只是一个例子,我认为您不想在模板引擎中处理光标位置。相反,我会说,只要有一个标记,您稍后会检测到它,并将其从渲染模板中删除,以将光标放置在该标记上。@Amber如果找不到这样的引擎,我将退回到该标记上。但是,拥有这样的令牌意味着我必须添加额外的不可回避规则才能对其进行转义,并将转义规则添加到已使用的模板引擎中,或者完全无法在生成的消息中使用此令牌。我使用的任何代币都会在“我引用了一条消息,其中引用了我写的关于该代币的消息”的情况下出现问题,例如,如果我在某个邮件列表上谈论新的电子邮件客户端,就会出现这种情况。无论如何,你都会遇到这个问题,因为模板引擎无法直接控制你的UI,所以他们仍然需要将某种令牌传递给应用程序的其余部分。
from mako.runtime import Context
class CursorContext(Context):
    __slots__=set(('lines', 'position'))

    def __init__(self, *args, **kwargs):
        super(CursorContext, self.__class__).__init__(self, self, *args, **kwargs)
        self.lines=['']
        self.position=None

    def write(self, v):
        ls=s(v).split('\n')
        self.lines[-1]+=ls.pop(0)
        self.lines+=ls

    def _record_position(self):
        if self.position is not None:
            raise ValueError('Position already defined')
        self.position=(len(self.lines), len(self.lines[-1]) if self.lines else 0)

    def _get_position(self):
        if self.position is None:
            self._record_position()
        return self.position

<...>

context=CursorContext(**env) # env is a dictionary with template environment variables
template.render_context(context) # template is mako.template.Template object
# Now template is in context.lines and 
# cursor position can be obtained by context._get_position()