GRAV cms Twig访问主题蓝图yaml中的特定数组索引

时间:2018-05-11 13:12:15

标签: twig yaml grav

我有一个主题,它在配置文件中保存了一些配置值:

enabled: true
dropdown:
  enabled: true

motto: 'il desiderio di coltivare.'
color1: '#0522ff'
color2: '#ff0000'
custom_logo:
  user/themes/terretinte/images/ttlogoh.svg:
    name: ttlogoh.svg
    type: image/svg+xml
    size: 3416
    path: user/themes/terretinte/images/ttlogoh.svg

访问我在树枝中使用的custom_logo路径:

<img src="{{config.themes.terretinte.custom_logo|first.path}}" alt="Terre Tinte" width="160" height="38">

我的问题是: 这是正确的方法吗? 因为“config.themes.terretinte.custom_logo”返回一个数组...我不能只指定索引值而不是第一个? (即在我需要的价值是第二个的情况下) 我试过了:

{{config.themes.terretinte.custom_logo[0].path}} -- doesn't work
{{config.themes.terretinte.custom_logo(0).path}} -- doesn't work
{{config.themes.terretinte.custom_logo|path}} -- doesn't work
{{config.themes.terretinte.custom_logo.path}} -- doesn't work

在没有迭代for循环所有键的情况下,在任何位置访问特定键的最佳方法是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

您的YAML语法实际上创建了子对象,而不是列表。在撰写本答案时,您的YAML条目为:

custom_logo:
  user/themes/terretinte/images/ttlogoh.svg:
    name: ttlogoh.svg
    type: image/svg+xml
    size: 3416
    path: user/themes/terretinte/images/ttlogoh.svg

通过使用[]表示法,您尝试将其作为数组进行访问,但实际上并未创建数组。相反,您已经创建了一个子变量。我不完全确定twig如何处理变量名中的/,但由于它不会抛出错误,所以它可能很好。根据您的处理方式,此修复程序会略有变化。

您真的想在阵列中使用多个自定义徽标吗?

对我来说,一个主题会有多个徽标似乎有些奇怪。如果您只使用第一个,则没有理由创建数组。这是一个简单的解决方法。

custom_logo:
  name: ttlogoh.svg
  type: image/svg+xml
  size: 3416
  path: user/themes/terretinte/images/ttlogoh.svg

user/themes/terretinte/images/ttlogoh.svg:之一已删除,我们现在可以更轻松地访问每个变量。

<img src="{{config.themes.terretinte.custom_logo.path}}" alt="Terre Tinte" width="160" height="38">

如果您确实需要索引中的多个徽标

如上所列,使用带有:的文本字段可创建命名变量。如果我们只删除整行并用-替换它,我们现在有一个可索引的数组。添加尽可能多的-

custom_logo:
  -       
    name: ttlogoh.svg
    type: image/svg+xml
    size: 3416
    path: user/themes/terretinte/images/ttlogoh.svg

您真的想要命名徽标吗?

我实际上可以想到一些您需要多个徽标的案例。话虽如此,我不确定你何时想要在数组中看到它们,而不是命名变量。下面是一个示例,说明如何使用多个已命名的徽标,然后将其用于树枝。

custom_logo:
  normal:
    name: ttlogoh.svg
    type: image/svg+xml
    size: 3416
    path: user/themes/terretinte/images/ttlogoh.svg
  black_and_white:
    name: ttlogoh_bw.svg
    type: image/svg+xml
    size: 3416
    path: user/themes/terretinte/images/ttlogoh_bw.svg

然后可以将这些引用为:

<img src="{{config.themes.terretinte.custom_logo.normal.path}}" alt="Terre Tinte" width="160" height="38">
<img src="{{config.themes.terretinte.custom_logo.black_and_white.path}}" alt="Terre Tinte" width="160" height="38">