【问题标题】:Render cherrypy's template with id/hash使用 id/hash 渲染cherrypy的模板
【发布时间】:2013-03-12 19:28:23
【问题描述】:

如何呈现页面并转到特定 id?

现在我有这个代码的以下功能:

@cherrypy.expose
@require
def page():
    tmpl = lookup.get_template('page.html')
    return tmpl.render()

但是,现在page.html 确实有几个子页面,我可以通过像mydomain.com/page#someid 这样的 URL 访问它们。

有没有办法渲染一个模板直接去id?

【问题讨论】:

  • URL 上的#id 有什么问题?。您能否提供更多关于您为什么要这样做的背景信息?
  • 好吧,#id 没什么问题,我只是不知道该怎么做,因为我正在访问模板,这是一个 .html 文件,我做不到类似lookup.get_template('page.html#id')。而且我不知道如何将#id 放入tmpl.render()。

标签: javascript python cherrypy


【解决方案1】:

我认为您正在混淆这些想法,URL 的 # 部分是客户负责关注特定元素 ID 的职责。不过,我想您想通过 javascript 动态嵌入页面特定部分的块,我可以考虑两种可能性:

一,用来自不同子模板的不同id组成整页模板,如果你使用模板模块,这很容易,比如mako,并制作一个cherrypy处理程序来返回各个部分,这是当然,假设您可以控制页面的内容并且 id 不是动态的(从 db 或其他东西生成)并且主站点是一堆includes。

@cherrypy.expose
def page_part(section):
    tpl_name = 'page_%s.html' % section
    # validate that the template exists, then:
    tmpl = lookup.get_template(tpl_name)
    return tmpl.render()

Mako 模板:

page.html:

<html>
  <body>
     <div id="main">
          This is the main content of the site!
      </div>
      <h4>Sections</h4> 
      <div id="section_1">
       <%include file="page_section1.html" />
      </div>

      <div id="section_2">
       <%include file="page_section2.html" />
      </div>
 </body>
</html>

page_section1.html:

<p> Content of section 1</p>

page_section2.html:

<p> Content of section 2</p>

或者二,使用jQuery选择器或类似的东西来请求页面一次并在返回的html中进行子选择。

$.get('/page.html', 
      function(data){
          $('#this_page_id').html($('#sect_in_other_page', $(data)).html());
      });

【讨论】:

  • 我实际上正在使用mako。将对此进行调查。先谢谢了。
  • 您能否详细解释一下,使用mako 的第一种方法如何工作?如果我要加载我的page.html,我如何附加页面 ID,例如sectOne?
  • @cherrun 我希望答案的改进可以澄清这个想法。
  • 抱歉,我不明白这是怎么回事。当我运行tpl_name = 'page_%s.html.' %section 然后return tpl.render() 我肯定只会得到那个具体的,例如page_section1.html 文件,但不是整个 page.html 文件,然后它会跳转到 section1。它只会呈现那一页,而不会呈现所有其他页面。
  • 基本上,如果不使用 javascript 或在 URL 中指定,您无法控制客户端如何聚焦到特定元素。在 js 中,您可以执行 document.location = '#mi_elem_id' ,这将专注于元素。
猜你喜欢
  • 2014-12-25
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 2016-11-13
  • 2012-09-08
  • 2010-10-28
  • 2011-12-27
  • 1970-01-01
相关资源
最近更新 更多