InternalLoader.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright 2017, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Stencil
  17. import Foundation
  18. // A class for loading Stencil templates from compiled-in representations
  19. public class InternalLoader: Loader {
  20. private var templates: [String:String]
  21. public init() {
  22. self.templates = loadTemplates()
  23. }
  24. public func loadTemplate(name: String, environment: Environment) throws -> Template {
  25. if let encoding = templates[name],
  26. let data = Data(base64Encoded: encoding, options:[]),
  27. let template = String(data:data, encoding:.utf8) {
  28. return environment.templateClass.init(templateString: template,
  29. environment: environment,
  30. name: name)
  31. } else {
  32. throw TemplateDoesNotExist(templateNames: [name], loader: self)
  33. }
  34. }
  35. public func loadTemplate(names: [String], environment: Environment) throws -> Template {
  36. for name in names {
  37. if let encoding = templates[name],
  38. let data = Data(base64Encoded: encoding, options:[]),
  39. let template = String(data:data, encoding:.utf8) {
  40. return environment.templateClass.init(templateString: template,
  41. environment: environment,
  42. name: name)
  43. }
  44. }
  45. throw TemplateDoesNotExist(templateNames: names, loader: self)
  46. }
  47. }