json 如何在html脚本中调用thymeleaf自定义方言

dkqlctbz  于 2023-11-20  发布在  其他
关注(0)|答案(3)|浏览(128)

所以基本上我尝试使用ld+json通过thymeleaf构建一个动态模式。为了检索相应页面的url,我们设置了一个自定义处理器:

public class QuackUrlAttributeTagProcessor extends AbstractAttributeTagProcessor {
    private static final String ATTR_NAME = "quackToHref";
    private static final int PRECEDENCE = 10000;

    @Autowired
    private ApplicationPropertyAccess applicationProperties;

    /**
     * Constructs a new processor.
     *
     * @param dialectPrefix the prefix to use if not the standard defined by the dialect
     */
    public QuackUrlAttributeTagProcessor(final String dialectPrefix) {
        super(
            TemplateMode.HTML, // This processor will apply only to HTML mode
            dialectPrefix,     // Prefix to be applied to name for matching
            null,              // No tag name: match any tag name
            false,             // No prefix to be applied to tag name
            ATTR_NAME,         // Name of the attribute that will be matched
            true,              // Apply dialect prefix to attribute name
            PRECEDENCE,        // Precedence (inside dialect's precedence)
            true);             // Remove the matched attribute afterwards
    }

    /**
     * Performs the actual task of the processor. This will use quack data to construct an Url path.
     */
    @Override
    protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag,
            final AttributeName attributeName, final String attributeValue,
            final IElementTagStructureHandler structureHandler) {
        IEngineConfiguration configuration = context.getConfiguration();
        IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
        IStandardExpression expression = parser.parseExpression(context, attributeValue);

        Quack quack = (Quack)expression.execute(context);
        String url = QuackManager.buildUrlPath(quack);

        structureHandler.setAttribute("href", applicationProperties.getFrontendBaseUrl() + url);
    }
}

字符串
习惯方言:

public class XContDialect extends AbstractProcessorDialect implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    /**
     * Constructor that will define the name of the Dialect.
     */
    public XConDialect() {
        super("XConsult Dialect", "xc", 1000);
    }

    /**
     * Initialise the dialect's processors.
     *
     * Note the dialect prefix is passed here because, although "xc" is set to be the dialect's prefix in the
     * constructor, that only works as a default, and at engine configuration time the user might have chosen
     * a different prefix to be used.
     */
    public Set<IProcessor> getProcessors(final String dialectPrefix) {
        final Set<IProcessor> processors = new HashSet<IProcessor>();

        QuackUrlAttributeTagProcessor processor = new QuackUrlAttributeTagProcessor(dialectPrefix);
        AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
        factory.autowireBean(processor);

        processors.add(processor);
        return processors;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}


这样我就可以在html模板中添加属性,如下所示:

<html xmlns:th="http://www.thymeleaf.org" xmlns:xc="http://www.example.de">

 <link rel="canonical" xc:quackToHref="${quack}" />


这会正确设置href-attribute。现在ld+json脚本看起来如下:

<script type="application/ld+json">

    /*<![CDATA[*/

    {
      "@context": "https://schema.org",
      "@graph": [
        {
          "@type": "Article",
          "url": "[[xc:quackToHref="${quack}"]]",
          "isPartOf": { "@id": "test" },
          "author": {
            "name": "[[${article.nickname}]]",
            "@id": "https://example.de/profile/[[${article.authorId}]]"
          },          
        },
       
        ]
      }

    /*]]>*/

  </script>


什么抛出错误:

Caused by: org.attoparser.ParseException: Could not parse as expression: "xc:quackToHref="${quack}" (template: "articlequack" - line 38, col 22)


显然,在脚本中调用自定义处理器是不可能的。有人知道如何获取CDATA中的URL吗?

fumotvh3

fumotvh31#

如果要在文本模板模式中使用属性,语法应该如下所示:

[# xc:quackToHref="${quack}" /]

字符串

wf82jlnq

wf82jlnq2#

试试这个

<script type="application/ld+json">

    {
      "@context": "https://schema.org",
      "@graph": [
        {
          "@type": "Article",
          "url": "[[${applicationProperties.frontendBaseUrl}]]${quack}", 
          "isPartOf": { "@id": "test" },
          "author": {
            "name": "[[${article.nickname}]]",
            "@id": "https://example.de/profile/[[${article.authorId}]]"
          }         
        }
      ]
    }

   

</script>

字符串

  • 确保在模板中使用applicationProperties.frontendBaseUrl变量的位置可以访问该变量。
  • 正确使用Thymeleaf表达式:检查您是否在模板中正确使用了Thymeleaf表达式,例如[[...]]${...}.

试试这个,让我知道如果没有解决的评论在这里..

mefy6pfw

mefy6pfw3#

要在HTML模板中使用自定义Thymeleaf方言,您需要在项目中包含方言,配置它,然后在HTML文件中使用它。以下是在HTML脚本中调用自定义Thymeleaf方言的步骤:

  • 将自定义方言添加到项目中:
  • 首先,你需要通过实现org.thymeleaf.dialect.IDialect接口来创建一个自定义的Thymeleaf方言。这涉及到定义你自己的处理器、属性或方言将处理的标签。
  • 配置Thymeleaf以使用自定义方言:
  • 在您的项目配置(例如,Sping Boot 应用程序)中,您可以配置Thymeleaf以包含您的自定义方言。以下是如何在Sping Boot 应用程序的application.propertiesapplication.yml文件中使用自定义方言配置Thymeleaf的示例:
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.servlet.cache=true
spring.thymeleaf.servlet.order=1
spring.thymeleaf.check-template-location=true
spring.thymeleaf.template-resolver-order=1
spring.thymeleaf.cache-names=cache
spring.thymeleaf.dialects.custom-dialect=your.package.CustomDialect

字符串
在本例中,通过指定自定义方言的包和类名来配置Thymeleaf方言。

  • 在HTML模板中使用自定义方言:
  • 在HTML模板中,您现在可以使用自定义方言的功能。例如,如果您的自定义方言添加了自定义属性或标记,则可以按如下方式使用它:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:custom="http://www.example.com/thymeleaf-custom-dialect">
<head>
    <title>Custom Dialect Example</title>
</head>
<body>
    <div custom:yourAttribute="someValue">Custom Dialect Attribute</div>
    <custom:customTag>Custom Dialect Tag</custom:customTag>
</body>
</html>


http://www.example.com/thymeleaf-custom-dialect替换为自定义方言的命名空间URI。

  • 构建并运行您的应用程序:
  • 在HTML模板中配置和使用自定义方言后,构建并运行应用程序。自定义方言的功能将在渲染期间应用于Thymeleaf模板。

确保自定义方言在应用程序中正确实现并注册,以使其按预期工作。此外,确保在HTML模板中使用正确的命名空间和语法来调用自定义方言的功能。

相关问题