Odoo 15/16 XPath引用问题:16版本t标签定位失败求助
Odoo 16 中 XPath 定位节点的问题解决
背景
在Odoo 15中,结账按钮的模板代码如下:
<a role="button" t-if="website_sale_order and website_sale_order.website_order_line" class="btn btn-primary float-right d-none d-xl-inline-block" href="/shop/checkout?express=1"> <span>Process Checkout</span> <span class="fa fa-chevron-right" /> </a>
对应的继承视图XPath可以正常定位并控制按钮显示:
<template id="zhen_product_cart_line_validate_button" inherit_id="website_sale.cart"> <xpath expr="//a[@href='/shop/checkout?express=1']" position="attributes"> <attribute name="t-att-style">'' if website.zhen_products_validation() else 'display:none;'</attribute> </xpath> </template>
问题
升级到Odoo 16后,官方模板将跳转地址改为通过t-set变量定义:
<t t-set="redirect_url" t-value="'web/login?redirect=/shop/checkout' if redirect_to_sign_in else '/shop/checkout?express=1'"/>
尝试用以下XPath定位该t节点时,升级模块报错:
<xpath expr="//t[@t-value='/shop/checkout?express=1']" position="attributes">
错误信息:
Element '<xpath expr="//t[@t-value=&#39;/shop/checkout?express=1&#39;]">' cannot be located in parent view
解决方法
1. 错误原因
原XPath无法匹配的核心原因是:t-value的属性值是完整的三元表达式字符串,而非单独的'/shop/checkout?express=1'分支内容,直接匹配属性值等于该字符串自然找不到目标节点。
2. 正确定位t-set节点
如果你的需求是修改redirect_url变量的值,可通过t-set的变量名来准确定位(变量名redirect_url是官方固定定义,稳定性更高):
<template id="zhen_product_cart_line_validate_button" inherit_id="website_sale.cart"> <xpath expr="//t[@t-set='redirect_url']" position="attributes"> <!-- 此处添加你的属性修改逻辑 --> </xpath> </template>
3. 回归原需求:控制结账按钮显示
如果你的核心需求还是和Odoo 15一样,控制结账按钮的显示状态,那么应该定位使用redirect_url的按钮节点,而非t-set变量节点。Odoo 16中按钮的模板代码已改为通过t-att-href绑定redirect_url,对应的XPath定位如下:
<template id="zhen_product_cart_line_validate_button" inherit_id="website_sale.cart"> <xpath expr="//a[@t-att-href='redirect_url' and @role='button']" position="attributes"> <attribute name="t-att-style">'' if website.zhen_products_validation() else 'display:none;'</attribute> </xpath> </template>
该XPath通过按钮的role="button"特征和t-att-href="redirect_url"属性组合定位,能精准匹配目标按钮,同时避免官方后续调整表达式内容导致的定位失效问题。
内容的提问来源于stack exchange,提问作者Ahmed Haroon
相关产品推荐
相关产品推荐

