5

I recently started making web apps, and while I make some stuff that works, I'm not sure of the best practices.

Up to now, I've mostly used the templating systems of Django, web.py and PHP. But now that I'm using jQuery and nice ajaxy magic to get data from the server without refreshing the client, I'm seeing the advantages of building the HTML directly in javascript (so I can just send a small json object to the client and have him figure out what to change and how).

So now I have some bits that are rendered with templates, and some that are built in javascript, and even one horrid case where there's a mix of both, a web.py template that generates a javascript function that creates a HTML table - feels like C macros all over again! (I'll refactor that away eventually)

Is this a common problem in web development? Any recommended best practices, such as "use json for everything, render as much as possible in javascript", "use library foo", etc.? Any good heuristics for what to handle with templates, and what to handle with javascript?

Searching a bit here, I found someone asking about javascript templates, which does seem like a possible solution.

4

5 回答 5

4

Please, don't use Javascript to layout your pages. Only use it where it is needed.

Despite recent enhancements and standardizations, Javascript is still typically slow, difficult to be completely compatible (think old IE and others), and not so compatible with some screen readers and scrapers/search engines.

If you can do it by returning straight-up HTML, then that is typically the way you want to go.

于 2010-11-21T20:04:34.037 回答
2

这里有一个稍微相关的问题

您可以为两者使用相同的模板 -这个库看起来很有趣。

您只能在服务器上呈现模板......上面的问题有一种方法可以有效地做到这一点。

如有必要,您可以在 javascript 中复制某些模板 - 尝试jqtemplate

就个人而言,我可能只会在服务器端呈现 HTML,以避免模板重复。如果我的服务器更像是一个 JSON Web 服务,我会做 JS 模板,可能还为其他客户端提供服务。

也就是说,如果您的网站可访问且对 js 不友好对您很重要(应该如此),那么在没有 js 的情况下完全编写您的网站,然后逐步增强它。

于 2010-11-22T17:02:25.823 回答
1

前段时间我遇到了同样的麻烦。我有一个网页,它使用 web.py 模板呈现一些东西,它有 ajax 分页。所以它必须使用 javascript 渲染下一页。我最终扩展了 web.py 模板引擎以生成一个 javascript 函数来呈现相同的模板输出。

有关更多详细信息,请参阅此博客文章:

http://anandology.com/blog/javascript-templating-with-webpy/

于 2010-11-22T16:48:09.620 回答
1

永远不要将您网站的功能基于 javascript。如果这样做,您将失去所有关闭 javascript 的访问者。如果你真的想要,你需要检测关闭 javascript 的用户,然后重定向他们;或提供<noscript>替代方案。此外,虽然爬虫现在可以解析 javascript,但它仍然对网站的 SEO 造成了巨大的损害。还有兼容性和开销问题,这可能是当今移动设备、上网本等的问题。

于 2010-11-21T21:16:48.057 回答
1

AngularJS是一种流行的客户端模板解决方案,这是我在问了这个问题多年后才发现的。您可以像在 Django 中那样编写 HTML 模板(“部分”),然后让 javascript 获取并根据需要解释它们 - 这样您就可以得到两全其美的动态网站,一个代码和布局清晰分离的动态网站。

于 2015-07-02T13:38:18.013 回答