多个网站的Go HTML模板

huangapple go评论83阅读模式
英文:

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 == &quot;simple&quot; %}
        &lt;p&gt;We don&#39;t show any image in the simple theme.&lt;/p&gt;
    {% else %}
        {# This would lead to a database call and return the image path #}
        &lt;img src=&quot;{{ service.ImageURL() }}&quot; /&gt;
    {% 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.

huangapple
  • 本文由 发表于 2014年8月16日 21:35:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/25340673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定