英文:
Go HTML templates for multiple sites
问题
我正在准备一个应用程序,该应用程序将为多个具有共同管理面板的站点提供服务(一个包含不同主题的页面,以简化操作)。
每个“主题”都有不同的需求。例如,虽然它们都显示服务列表,但其中一些还会显示相关联的图像。对于那些不需要显示图像的主题,我希望避免进行数据库调用(以便在渲染页面时使用不同的逻辑)。
在 Laravel(一个 PHP 框架)中,这将是使用视图组件的完美场景。
在 Go 语言中,这样一个系统的设计会是怎样的呢?
我在考虑一种类似于“钩子”的机制,每个主题都可以注册运行函数来获取并添加特定模板的数据。有没有更好的方法来实现这个呢?
英文:
I'm preparing an application that will serve several different sites that have a common admin panel (a page with different themes to simplify).
Each of these "themes" will have different needs. For example while all of them show a list of services, some of them will show an associated image too. For the ones who don't I would prefer to avoid the DB calls to fetch them (different logic to render the pages).
In Laravel (a PHP framework) this would be a perfect use for view composers.
What would be the design of such a system in go?
I was thinking in some kind of "hooks" that each theme can register to run functions to fetch and add data for a specific template. There's a better way to do it?
答案1
得分: 2
如果你将一个服务对象的列表传递给模板,你可以在模板内部轻松决定要显示什么。如果你决定显示一个服务的图片,你可以调用ServiceObject.ImageURL()
(这将导致数据库查询)。如果你不调用这个函数,就不会发出数据库查询。
使用pongo2模板引擎的示例:
{% for service in services %}
{% if page.theme == "simple" %}
<p>在简单主题中我们不显示任何图片。</p>
{% else %}
{# 这将导致数据库查询并返回图片路径 #}
<img src="{{ service.ImageURL() }}" />
{% endif %}
{% endfor %}
另一个想法是为每个主题创建一个单独的模板(扩展公共基础模板);这样你就不需要在模板内部检查主题了。
英文:
If you pass a list of service objects to the template, you could easily decide inside the template what you want to show. If you decide to show a service's image, you could call the ServiceObject.ImageURL()
(which would then lead to a database call). If you're not calling this function, there will be no database query issued.
A sample using the pongo2 template engine:
{% for service in services %}
{% if page.theme == "simple" %}
<p>We don't show any image in the simple theme.</p>
{% else %}
{# This would lead to a database call and return the image path #}
<img src="{{ service.ImageURL() }}" />
{% endif %}
{% endfor %}
Another idea would be to simply create an individual template per theme (extending the common base template); you don't have check for the theme inside the template then.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论