【问题标题】:dynamic templates/theming system for Angular appAngular 应用的动态模板/主题系统
【发布时间】:2016-01-06 06:46:42
【问题描述】:

我正在尝试在我的 Angular 应用程序中创建一个不错的动态主题系统。 基本上,我有一个 Wordpress 插件,您可以通过下拉列表为我的 Angular 应用程序选择您想要的主题(位于子文件夹中的同一服务器上),然后我通过 GET 参数传递主题,www.mywebsite.com/myapp /welcome?theme=white_theme,并且该文件夹中的 Angular 应用程序当前将在前端控制器中快速设置(我想我会将它移动到路由的 app.js 解析中,因此它发生在控制器之前,现在我只有解析设置默认主题):

var dynamic_theme = URI.parseQuery(query_string).theme; //url param gotten via URI js library
if(dynamic_theme) {
  $rootScope.theme_name = dynamic_theme;
} else {
  $rootScope.theme_name = 'default';
}

后来在 index.html 中,我通过 ng-href 包含动态主题:

<!-- build:css(.tmp) styles/generic.css -->
  <link rel="stylesheet" href="styles/generic.css">
<!-- endbuild -->
<link rel="stylesheet" ng-if="theme_name" ng-href="styles/themes/{{theme_name}}/main-theme.css">

但我也希望 .html 模板本身能够被每个主题的设计主题覆盖。 例如,在 app.js 中,要启动这个“问卷”应用程序,我已经定义了这个:

templateUrl: 'views/main.html',

在那个文件中,我有一个指令: 该指令使用模板“views/question.html” 在该文件中,我决定是否根据问题获取“views/templates/radio.tpl.html”、“views/templates/checkbox.tpl.html”、“views/templates/dropdown.tpl.html”-类型传递给指令。 像这样:

<div ng-include src="'views/templates/' + currentquestion.question_type + '.tpl.html'"></div>

我想也许我可以将主题传递到指令中(或者只是访问 $rootScope)并执行以下操作:

<div ng-include src="'views/templates/' + dynamic_theme + '/' + currentquestion.question_type + '.tpl.html'"></div>

我只是好奇这听起来是不是一个计划。或者有没有更好的方法来做到这一点(或者甚至是一个真正的主题解析器库/设置,你可以使用 Angular 来完成我试图手动实现的相同的事情)。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    好像有很多different ways to do this,看起来最有希望的是using templateUrl as a function

      templateUrl: function(elem,attrs){
          return 'views/templates/' + resolveTheme() + 'main.tpl.html';
      },
    

    您必须自己编写resolveTheme(),可能作为全局或服务。

    另类

    另一个选项,如果您可以预编译您的模板,您可以使用$templateCache 并动态加载正确的模板包。您需要确保在请求任何模板之前发生这种情况,因为 Angular 将对它无法找到的任何模板发出 HTTP 请求。

    这是预编译模板的一种方法: https://github.com/karlgoldstein/grunt-html2js

    然后您可以拥有多个模板包:template-theme1.jstemplate-theme2.js

    并且可以构建应用程序的多个版本,或者在您的应用程序代码之后(但在请求任何模板之前)包含这些模板。

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多