Template.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import moment from 'moment';
  2. export default class Template {
  3. constructor() {
  4. this.templatePattern = {
  5. 'year': this.getYear,
  6. 'month': this.getMonth,
  7. 'date': this.getDate,
  8. 'user': this.getUser,
  9. };
  10. }
  11. getYear() {
  12. return moment().format('YYYY');
  13. }
  14. getMonth() {
  15. return moment().format('YYYY/MM');
  16. }
  17. getDate() {
  18. return moment().format('YYYY/MM/DD');
  19. }
  20. getUser() {
  21. return '/user/sotarok';
  22. }
  23. getPageName(pageNameTemplate) {
  24. let pageName = pageNameTemplate;
  25. Object.keys(this.templatePattern).forEach(key => {
  26. const matcher = new RegExp(`{${key}}`, 'g');
  27. if (pageName.match(matcher)) {
  28. const replacer = this.templatePattern[key]();
  29. pageName = pageName.replace(matcher, replacer);
  30. }
  31. });
  32. return pageName;
  33. }
  34. process(code, lang) {
  35. const templateId = new Date().getTime().toString(16) + Math.floor(1000 * Math.random()).toString(16);
  36. let pageName = lang;
  37. if (lang.match(':')) {
  38. pageName = this.getPageName(lang.split(':')[1]);
  39. }
  40. return `<button class="template-create-button btn btn-primary" data-template="${templateId}" data-path="${pageName}">${pageName} のページを作成する</button>
  41. <pre><code id="${templateId}" class="lang-${lang}">${code}\n</code></pre>\n`;
  42. }
  43. }